实现 ES6 的 class extend 继承

1,433 阅读1分钟

先了解两个方法

  • Object.create()方法创建一个新对象,使用现有的对象来提供新创建的对象的__proto__。
  • call() 方法使用一个指定的 this 值和单独给出的一个或多个参数来调用一个函数。

ES6 继承

class Base {
  constructor(name = "") {
    this.name = name;
  }
  getName() {
    return this.name;
  }
}

class Person extends Base {
  constructor(name) {
    super(name);
  }
}

new Person ('jkm')
  • 观察 new 出来的对象结构

image.png

实现

function Base(name = "") {
  this.name = name;
}
Base.prototype.getName = function() {
  return this.name;
};

function Person(name = "") {
  Base.call(this, name);
}
Person.prototype = Object.create(Base.prototype);
Person.prototype.constructor = Person;

console.log(new Person("jkm"));
  • 结果与上面 ES6 语法的一致 image.png