In the example below I noticed the comment "fixes the delegated constructor reference" and I'm curious -how can I show this "not working / then working after I add that line of javascript?
full gist here => https://gist.github.com/getify/5572383
Thank you in advance
function Foo(who) {
this.me = who;
}
Foo.prototype.identify = function() {
return "I am " + this.me;
};
function Bar(who) {
Foo.call(this,"Bar:" + who);
}
Bar.prototype = Object.create(Foo.prototype);
Bar.prototype.constructor = Bar; // "fixes" the delegated `constructor` reference
Functions in javascript are actually objects. When we create any function Foo in Javascript, the interpreter automatically creates a prototype property Foo.prototype, which is itself an object. The interpreter then creates a constructor property on this object which refers to Foo itself:
console.log(Foo.prototype.constructor); // reference to Foo;
console.log(Foo.prototype.hasOwnProperty("constructor")); // TRUE;
This same process takes place when we create the Bar function. But later we introduce a difference. The difference is that we manually overwrite the object at Bar.prototype with this code:
Bar.prototype = Object.create(Foo.prototype);
Now Bar.prototype has a new object that we created manually. This new object does not have a constructor property because it was created by us and not the interpreter:
console.log(Bar.prototype.hasOwnProperty("constructor")); // FALSE
So Bar.prototype does not have its own constructor property but Foo.prototype does. Next, imagine that we create an instance of Bar:
var myBar = new Bar();
myBar.constructor is an inherited property that does not exist on the myBar object. If we try to access it, the javascript interpreter searches up the prototype chain for the constructor property. It does not find one on Bar.prototype because we overwrote that object. The interpreter continues searching and eventually finds the property on Foo.prototype. As a result, any reference to myBar.constructor will refer to Foo.prototype.constructor, which contains a reference to Foo:
console.log(myBar.constructor); // reference to Foo
So this is why we explicitly set Bar.prototype.constructor manually, so that when traversing the prototype chain, the interpreter will find a constructor property on Bar.prototype as it would have if we hadn't overwritten it:
Bar.prototype.constructor = Bar;
The end result is more useful behavior on our objects:
var myBar2 = new Bar();
console.log(myBar2.constructor); // reference to Bar
This issue should not come up often as it is somewhat rare that one would need to check the constructor property of an object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With