原型继承:Object.create vs Object.assign
Prototypal inheritance: Object.create vs Object.assign
我目前正在阅读 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"
我明白 link 是在行
Bar.prototype = Object.create(Foo.prototype);
这样Bar的原型指向一个原型为Foo.prototype
的对象。
我想知道为什么我们不这样做:
Bar.prototype = Object.assign({}, Foo.prototype);
我们得到了相同的结果,现在我们对所有方法都有一层原型链查找,而不是两层。
We achieve the same result
不,我们没有。 Bar.prototype
将 而不是 从 Foo.prototype
继承,而是拥有自己的属性。当然,来自 Foo.prototype
的值会被复制过来,但这只是 Foo.prototype
的 快照 从调用 Object.assign
时开始,而不是实时连接。
我目前正在阅读 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"
我明白 link 是在行
Bar.prototype = Object.create(Foo.prototype);
这样Bar的原型指向一个原型为Foo.prototype
的对象。
我想知道为什么我们不这样做:
Bar.prototype = Object.assign({}, Foo.prototype);
我们得到了相同的结果,现在我们对所有方法都有一层原型链查找,而不是两层。
We achieve the same result
不,我们没有。 Bar.prototype
将 而不是 从 Foo.prototype
继承,而是拥有自己的属性。当然,来自 Foo.prototype
的值会被复制过来,但这只是 Foo.prototype
的 快照 从调用 Object.assign
时开始,而不是实时连接。