1. class Person {
    2. static instance = null; // 静态属性: => Person.instance
    3. static getInstance() { // 静态方法
    4. return super.instance;
    5. }
    6. /* 下面的代码等价于
    7. name1 = 'mao';
    8. age1 = 23;
    9. */
    10. constructor(name, age) { // 构造函数
    11. this.name = name; // 私有(实例)属性
    12. this.age = age;
    13. };
    14. sayHi() { // 类方法: Person.prototype.sayHi,不可枚举
    15. console.log(this);
    16. console.log('hi');
    17. }
    18. sayHello = () => { // 箭头函数:this.sayHello:私有方法
    19. console.log(this);
    20. console.log('hello');
    21. }
    22. sayBye = function () { // this.sayBye
    23. console.log('bye');
    24. }
    25. }

    几个特点:

    1. 通过 class 创建的函数具有特殊的内部属性标记 [[FunctionKind]]:"classConstructor"。因此,它与手动创建并不完全相同。
      编程语言会在许多地方检查该属性。例如,与普通函数不同,必须使用 **new** 来调用它
    1. 类方法不可枚举。 类定义将 "prototype" 中的所有方法的 enumerable 标志设置为 false
      这很好,因为如果对一个对象调用 for..in 方法,通常不希望 class 方法出现。
    1. 类总是使用 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. **解决办法**:
    2. 1. 传递一个包装函数,例如 `setTimeout(() => button.click(), 1000)`
    3. 1. 将方法绑定到对象,例如在 constructor 中。
    4. 1. `类字段(class field)` 提供了另一种非常优雅的语法:
    5. - 类字段 `click = () => {...}` 是**基于每一个对象**被创建的,每一个 `Button` 对象都有一个独立的方法,在内部都有一个指向此对象的 `this`。可以把 `button.click` 传递到任何地方,而且 `this` 的值总是正确的。**在浏览器环境中,它对于进行事件监听尤为有用。**
    6. ```javascript
    7. class Button {
    8. constructor(value) {
    9. this.value = value;
    10. }
    11. click = () => { // class field
    12. alert(this.value);
    13. }
    14. }
    15. let button = new Button("hello");
    16. setTimeout(button.click, 1000); // hello