Prev: FAQ Topic - How do I protect my javascript code? (2010-01-13)
Next: How to copy multi object array contents into single object arrays?
From: Dolaameng on 13 Jan 2010 04:30 I am reading the book <Professional javascript for web developers> by Nicholas C. Zakas. On page 162 he gives an example of how overwriting the prototype with an object literal can cause the constructor testing to fail. Here is the code in the book, /////////////////////////////////////////////////// function Person(){ } Person.prototype = { name : "Nicholas", age : 29, job : "Software Engineer", sayName : function () { alert(this.name); } }; var person = new Person(); alert(person.constructor == Person); //false alert(person instanceof Person); //true /////////////////////////////////////////////////// As the author explained, the prototype of the constructor Person has been overwritten by an object literal. As a result, person.constructor will not evaluate to Person anymore ( it is Object now) and somehow the instanceof operator still works. Everything seems straightforward. But something interesting happened when I tried the code myself and changed the execution order of the two code snippets by accident-- I put the line of creating a new instance "var person = new Person();" BEFORE the overwriting of prototype, so it is now, /////////////////////////////////////////////////// function Person(){ } var person = new Person(); //now before the prototype overwriting Person.prototype = { name : "Nicholas", age : 29, job : "Software Engineer", sayName : function () { alert(this.name); } }; alert(person.constructor == Person); //true alert(person instanceof Person); //false /////////////////////////////////////////////////// As a consequence, the testing for person.constructor evaluates to true while the instanceof operator evaluates to false now. So I guess this is what is going on behind the scenes--everytime when a new instance is created by the constructor, the instance's hidden __proto__ property will be dynamically set to the current prototype property of the constructor. That is why in the second code the instance person's constructor still points to Person. And the 'instanceof' works somehow like this: it compares the instance's hidden __proto__ against the prototype property of the constructor. If the constructor's prototype property is on the instance's __proto__ chain, it will evaluates to true. So as in the first code, even when the prototype's constructor property is not correctly set, the instanceof operator will still work. I am still not quite sure about these prototype and instanceof concepts. So any supplementary comments will be welcomed. |