How to show the delegated `constructor` reference issue in javascript? -


in example below noticed comment "fixes delegated constructor reference" , i'm curious -how can show "not working / working after add line of javascript?

full gist here => https://gist.github.com/getify/5572383

thank in advance

function foo(who) {     this.me = who; }  foo.prototype.identify = function() {     return "i " + this.me; };  function bar(who) {     foo.call(this,"bar:" + who); }  bar.prototype = object.create(foo.prototype); bar.prototype.constructor = bar;    // "fixes" delegated `constructor` reference 

functions in javascript objects. when create function foo in javascript, interpreter automatically creates prototype property foo.prototype, object. interpreter creates constructor property on object refers foo itself:

console.log(foo.prototype.constructor);                   // reference foo; console.log(foo.prototype.hasownproperty("constructor")); // true; 

this same process takes place when create bar function. later introduce difference. difference manually overwrite object @ bar.prototype code:

bar.prototype = object.create(foo.prototype); 

now bar.prototype has new object created manually. new object not have constructor property because created , not interpreter:

console.log(bar.prototype.hasownproperty("constructor")); // false 

so bar.prototype not have own constructor property foo.prototype does. next, imagine create instance of bar:

var mybar = new bar(); 

mybar.constructor inherited property not exist on mybar object. if try access it, javascript interpreter searches prototype chain constructor property. not find 1 on bar.prototype because overwrote object. interpreter continues searching , finds property on foo.prototype. result, reference mybar.constructor refer foo.prototype.constructor, contains reference foo:

console.log(mybar.constructor); // reference foo 

so why explicitly set bar.prototype.constructor manually, when traversing prototype chain, interpreter find constructor property on bar.prototype have if hadn't overwritten it:

bar.prototype.constructor = bar; 

the end result more useful behavior on our objects:

var mybar2 = new bar(); console.log(mybar2.constructor); // reference bar 

this issue should not come rare 1 need check constructor property of object.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -