在许多关于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)
?
答案 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+"");
}