ES6 Class

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 指向的正确性。这对于代码的可读性和逻辑一致性有帮助,也可以在某些情况下避免错误。

posted @   一个甜橙子  阅读(2)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
点击右上角即可分享
微信分享提示