I am currently reading Kyle Simpson's You Don't know JS, trying to understand the whole prototype pattern.
It says we can achieve prototypal inheritance between Foo and Bar as follows:
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"
I understand the link is made in the line
Bar.prototype = Object.create(Foo.prototype);
so that Bar's prototype points to an object whose prototype is Foo.prototype.
I was wondering why don't we just do this:
Bar.prototype = Object.assign({}, Foo.prototype);
We achieve the same result and now we have one level of prototype chain lookup for all methods instead of two.
Object.assign?Object.assign😉Foo.prototypewill not be reflected on your assigned prototype.Foo.prototype, you would not be able to use it.