极客时间返利平台,你可以在上边通过山月的链接购买课程,并添加我的微信 (shanyue94) 领取返现。
山月训练营之面试直通车 服务上线了,从准备简历、八股文准备、项目经历准备、面试、面经、面经解答、主观问题答复、谈薪再到入职的一条龙服务。

# 在 js 中如何实现继承

Issue

欢迎在 Gtihub Issue 中回答此问题: Issue 382 (opens new window)

有以下两种方法可实现继承

# class/extends

class Animal {
  constructor(name) {
    this.name = name;
  }

  hello() {
    console.log("hello");
  }
}

class Dog extends Animal {
  constructor(name, say) {
    super(name);
    this.say = say;
  }
}

# function/new

function Animal(name) {
  this.name = name;
}

Animal.prototype.hello = () => {
  console.log("hello");
};

function Dog(name, say) {
  // 01 继承属性
  Animal.call(this, name);
  this.say = say;
}

// 02 通过连接原型链完成继承
Dog.prototype = Object.create(Animal.prototype);

// 03 再加上 constructor
Dog.prototype.constructor = Dog;
// Reflect.defineProperty(Dog.prototype, "constructor", {
//  value: Dog,
//  enumerable: false, // 不可枚举
//  writable: true
// })
Last Updated: 11/27/2021, 6:11:48 PM