【发布时间】:2018-04-27 04:23:11
【问题描述】:
我目前正在阅读 Kyle Simpson 的《你不懂 JS》,试图理解整个原型模式。
它说我们可以实现 Foo 和 Bar 之间的原型继承,如下所示:
function Foo(name) {
this.name = name;
}
Foo.prototype.myName = function () {
return this.name;
};
function Bar(name, label) {
Foo.call(this, name);
this.label = label;
}
// here, we make a new `Bar.prototype`
// linked to `Foo.prototype`
Bar.prototype = Object.create(Foo.prototype);
// Beware! Now `Bar.prototype.constructor` is gone,
// and might need to be manually "fixed" if you're
// in the habit of relying on such properties!
Bar.prototype.myLabel = function () {
return this.label;
};
var a = new Bar("a", "obj a");
console.log(a.myName()); // "a"
console.log(a.myLabel()); // "obj a"
我明白链接是在该行中建立的
Bar.prototype = Object.create(Foo.prototype);
因此 Bar 的原型指向一个原型为 Foo.prototype 的对象。
我想知道为什么我们不这样做:
Bar.prototype = Object.assign({}, Foo.prototype);
我们获得了相同的结果,现在我们对所有方法都进行了一级原型链查找,而不是两级。
【问题讨论】:
-
你如何认为
Object.assign的原型链更短? -
@ScottMarcus 你可以用
Object.assign运行sn-p ???? -
它可能低一级,但它不是同一个对象 - 更改
Foo.prototype中的内容不会反映在您分配的原型上。 -
@destoryer 这不是,我同意。但我是说它产生了完全相同的继承效果。
-
如果你要在
Foo.prototype上添加一个函数,你将无法使用它。
标签: javascript prototype prototypal-inheritance