下面创建一个class
class Person {
name: string = "David";
age: number = 15;
static gender: string = "male";
sayName() {
console.log(this.name);
}
static sayGender() {
console.log(this.gender);
}
}
const p = new Person();
而下面的代码会被编译为这样
class Person {
constructor() {
this.name = "David";
this.age = 15;
}
sayName() {
console.log(this.name);
}
static sayGender() {
console.log(this.gender);
}
}
Person.gender = "male";
const p = new Person();
constructor 是一个方法,一个类中必须存在的,如果创建class的时候没有写,则会默认添加。这个方法是在 new Person() 时自动调用的,里面会传入一个this,指向构造出来的实例对象,就是p。
这种情况下,将创建两个实例对象,第一次this指向p,第二次this指向p2
const p = new Person();
const p2 = new Person();
再来看看下面的代码
class Person {
//这是定义两个属性,并限制了类型
name: string;
age: number;
static gender:string;
constructor(name: string, age: number) {
// 为两个属性赋值,name,age参数来自于 new Person()时传入的实参
this.name = name;
this.age = age;
}
//this指向实例
sayName() {
console.log(this.name);
}
//注意:静态方法的 这个this指向 Person类,而类身上只有一个gender属性
static sayName() {
console.log(this.name);
}
}
//p实例的 name = 小黄 ,age = 2
const p = new Person("小黄", 2);
//p2实例的 name = 小黑 ,age = 3
const p2 = new Person("小黑", 3);