ES6 Class

gardenOfCicy / 2025-02-21 / 原文

1. setter & getter

// ES6 Class
class PersonCl {
  constructor(fullName, birthYear) {
    this.fullName = fullName;
    this.birthYear = birthYear;
  }
  // 类里面的方法可以直接写在里面
  // 下面的方法都是实例方法,所有构造函数创建的实例都可以调用它们
  calcAge() {
    console.log(2037 - this.birthYear);
  }

  set fullName(name) {
    if (name.includes(' ')) this._fullName = name; //这个下划线好微妙,临时变量
    else alert(`${name} is not a full name!`);
  }
  get fullName() {
    return this._fullName;
  }
  // 而 静态方法 只有构造函数本身才能调用! Static Method
  static hey() {
    console.log('Hey there 😊');
    console.log('static method this:', this);
  }
}

const jessica = new PersonCl('Jessica Davis', 1999);
console.log(jessica.fullName);

静态方法只有构造函数本身才能调用。

2. Object.create() 中类的继承

  1. Student.prototype.constructor = Student; 的作用
    在代码中,Student.prototype = Object.create(Person.prototype); 这行代码让 Student.prototype 的原型指向了 Person.prototype,实现了原型链继承。但这也有一个副作用:Student.prototype 的 constructor 属性会指向 Person,而不是 Student。

具体原因:
Object.create(Person.prototype) 创建了一个新的对象,这个对象继承了 Person.prototype,因此它的 constructor 属性也指向 Person。
因为 Student.prototype 现在等于 Object.create(Person.prototype),所以 Student.prototype.constructor 默认指向 Person。
解决方法:
Student.prototype.constructor = Student; 手动将 Student.prototype 的 constructor 属性重新指向 Student 构造函数,这样就恢复了 constructor 指向的正确性。这对于代码的可读性和逻辑一致性有帮助,也可以在某些情况下避免错误。