类是什么
class Person {
//
}
typeof Person; // function
这段代码的编译结果:
var Person = /** @class */ (function () {
function Person() {
}
return Person;
}());
typeof Person; // function
这段编译结果显示出,class 是一个function语法糖,类的数据结构是函数,类本身就指向构造函数(Person === Person.prototype.constructor)。 用class的方式写代码,代码看起来会整洁一点(个人感觉)。
类的实例
class Person {
#name = '无名' // 私有变量 等同于 private name
age = 10 // 默认为公共变量 等同于 public age
constructor(name, age) {
this.#name = name;
this.age = age;
}
toSay() {
console.log(`我叫 ${this.#name},今年 ${this.age} 岁`)
}
toSayHi() {
console.log(`Hi `)
}
static toAllSay() { // 静态成员无需实例化,直接通过类名调用
console.log(`hello`)
}
}
// // 实例化例子
let boy = new Person('小明', 15)
boy.#name // 错,私有变量不可访问
boy.age // 对,15
boy.toSay() // 对,我叫小明,今年15岁
boy.toAllSay() // 错,静态成员不可实例化
boy.constructor === Person.prototype.constructor // true
// 类的直接调用
Person.toAllSay() // 对,hello
Person.prototype.toSayHi() // 对,Hi
Person.prototype.toSay() // 错,Cannot read private member #name from an object whose class did not declare it
Person.prototype.age // undefined
// 综上所述,等同于
Person = {
toAllSay() { },
prototype: {
#name, // 私有变量不可继承,不可被外部访问
age,
constructor() { },
toSay() { },
toSayHi() { }
}
}
// 当new一个实例时,只会继承prototype对象
由于类的方法都定义在prototype对象上面,所以类的新方法可以添加在prototype对象上面,而且这些属性都是可以被继承的。如果加上static关键词,就表示该方法不可以被实例继承,而是通过类来直接调用。