class Person {static instance = null; // 静态属性: => Person.instancestatic getInstance() { // 静态方法return super.instance;}/* 下面的代码等价于name1 = 'mao';age1 = 23;*/constructor(name, age) { // 构造函数this.name = name; // 私有(实例)属性this.age = age;};sayHi() { // 类方法: Person.prototype.sayHi,不可枚举console.log(this);console.log('hi');}sayHello = () => { // 箭头函数:this.sayHello:私有方法console.log(this);console.log('hello');}sayBye = function () { // this.sayByeconsole.log('bye');}}
几个特点:
- 通过
class创建的函数具有特殊的内部属性标记[[FunctionKind]]:"classConstructor"。因此,它与手动创建并不完全相同。
编程语言会在许多地方检查该属性。例如,与普通函数不同,必须使用 **new** 来调用它
- 类方法不可枚举。 类定义将
"prototype"中的所有方法的enumerable标志设置为false。
这很好,因为如果对一个对象调用for..in方法,通常不希望 class 方法出现。
- 类总是使用
use strict。 在类构造中的所有代码都将自动进入严格模式。- 如果一个对象方法被传递到某处,或者在另一个上下文中被调用,则
this将不再是对其对象的引用。(“丢失this”,这也是React事件中this丢失的原因) ```javascript class Button { constructor(value) { this.value = value; } click() { alert(this.value); } }
- 如果一个对象方法被传递到某处,或者在另一个上下文中被调用,则
let button = new Button(“hello”);
setTimeout(button.click, 1000); // undefined
**解决办法**:1. 传递一个包装函数,例如 `setTimeout(() => button.click(), 1000)`。1. 将方法绑定到对象,例如在 constructor 中。1. `类字段(class field)` 提供了另一种非常优雅的语法:- 类字段 `click = () => {...}` 是**基于每一个对象**被创建的,每一个 `Button` 对象都有一个独立的方法,在内部都有一个指向此对象的 `this`。可以把 `button.click` 传递到任何地方,而且 `this` 的值总是正确的。**在浏览器环境中,它对于进行事件监听尤为有用。**```javascriptclass Button {constructor(value) {this.value = value;}click = () => { // class fieldalert(this.value);}}let button = new Button("hello");setTimeout(button.click, 1000); // hello
