JavaScript:使用Object.create和Object.assign进行原型继承之间的区别

时间:2018-02-22 18:47:37

标签: javascript prototypal-inheritance

在许多关于JavaScript继承的教程中,包括Mozilla's,他们分配Sub.prototype = Object.create(Sup.prototype),声明Object.create将创建一个原型为Sup.prototype的新对象,并将其分配给Sub.prototype

我没有得到的是,为什么他们使用Sup.prototype分配原型为Object.create的对象,当他们可以分配Sup.prototype对象本身的克隆时,直接,如Sub.prototype = Object.assign({}, Sup.prototype)

1 个答案:

答案 0 :(得分:0)

使用Object.assign({}, Sup.prototype),它只会复制所拥有的属性,并且只有在它们可枚举的情况下才会复制。您正在失去Sup.prototype可能从中受益的任何继承。



function Top() {}

// This method is enumerable, but inherited by Sup
Top.prototype.top = function() {
  console.log("top")
};

function Sup() {}
Sup.prototype = Object.create(Top.prototype, {
  sup: { // This method is non-enumerable
    value: function() {
      console.log("sup")
    }
  }
});

// So far so good...
var sup = new Sup();
sup.top()
sup.sup();

function Sub() {}
Sub.prototype = Object.assign({}, Sup.prototype);

// Not so good anymore...
var sub = new Sub();

try {
  sub.top();
} catch (e) {
  console.log(e+"");
}
try {
  sub.sup();
} catch (e) {
  console.log(e+"");
}