使用class
关键字来定义一个类。对象中主要包含了两个部分:属性和方法。
class Person {// 定义实例属性name:string = 'glm';age:number = 1234;
}
const a = new Person();
console.log(a.name);
在属性前使用static
关键字可以定义类属性(静态属性)
class Person {// 定义实例属性name:string = 'glm';age:number = 1234;static school:string = "whatu";
}
const a = new Person();
console.log(a.name);
console.log(Person.school);
class Person {// 定义实例属性name:string = 'glm';age:number = 1234;static school:string = "whatu";say_fn1() {console.log("fn -- say_fn1");}static say_fn2() {console.log("fn -- say_fn2");}
}
const a = new Person();
console.log(a.name);
console.log(Person.school);
a.say_fn1();
Person.say_fn2();
构造函数
constructor
被称为构造函数。构造函数会在对象创建时被调用。在实例方法中,this
就表示当前的实例。在构造函数中当前对象就是当前新建的那个对象。可以通过this
向新建的对象中添加属性。
class Person {name:string;age:number;constructor(name:string, age:number) {this.name = name;this.age = age;}
}
const a = new Person('yh', 321);
console.log(a.name, a.age);
继承
使用继承后,子类会拥有父类所有的方法和属性。通过继承可以将多个类中共有的代码写在一个父类中。
- 如果希望在子类中添加一些父类中没有的属性或方法直接加在子类中即可。
- 如果在子类中添加了和父类相同的方法,则子类方法会覆盖掉父类原方法(重写)
class Person {name:string;age:number;constructor(name:string, age:number) {this.name = name;this.age = age;}
}
class Student extends Person {info() {console.log("学生:" + this.name);}
}
const stu = new Student('glm', 14);
stu.info();
super
子类通过 super
关键字调用父类的构造函数和方法。super
关键字在子类的构造函数中用于调用父类的构造函数,在方法中用于调用父类的方法。
class Person {name:string;age:number;constructor(name:string, age:number) {this.name = name;this.age = age;}say() {console.log("this is Father_Class");}
}
class Student extends Person {uid:string;constructor(name:string, age:number, uid:string) {super(name, age);this.uid = uid;}info() {console.log("学生:" + this.name);}say() {super.say();console.log("this is Child_Class");}
}
const stu = new Student('glm', 14, "2345");
stu.say();
https://blog.csdn.net/qq_45590504/article/details/142503245?ops_request_misc=%257B%2522request%255Fid%2522%253A%25223ADDA7B1-A0FD-41B7-BFA8-21C3B9193504%2522%252C%2522scm%2522%253A%252220140713.130102334…%2522%257D&request_id=3ADDA7B1-A0FD-41B7-BFA8-21C3B9193504&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2allsobaiduend~default-1-142503245-null-null.142v100pc_search_result_base1&utm_term=typescript%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1&spm=1018.2226.3001.4187