我目前正在阅读凯尔·辛普森的“你不了解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);
我们取得了相同的结果,现在我们有一个层次的原型链查找所有的方法,而不是两个。
发布于 2018-04-26 20:23:11
我们取得了同样的结果
不,我们没有。Bar.prototype就不会继承Foo.prototype,而是会有自己的属性。当然,将复制来自Foo.prototype的值,但这只是调用Object.assign时的Foo.prototype快照,而不是活动连接。
https://stackoverflow.com/questions/50050937
复制相似问题