Reputation: 299
1.
function MyConstructor() {}
var myobject = new MyConstructor();
MyConstructor.prototype = {protest:"maizere"};
[ myobject instanceof MyConstructor, // false !
myobject.constructor == MyConstructor, // true !
myobject instanceof Object ] // true
console.log(myobject.protest) //undefined
This proves that myobject does not inherit properties and method from MyConstructor prototype anymore.
But see next code below:
2.
function MyConstructor() {}
var myobject = new MyConstructor();
MyConstructor.prototype.protest= "Maizere";//Do this line gets hoisted?or something else
[ myobject instanceof MyConstructor, // true!
myobject.constructor == MyConstructor, // true !
myobject instanceof Object ] // true
console.log(myobject.protest) //Maizere
Why is this happening?what is the exact definition of internal prototype?This also proves even after the instantiation of the object , proto is refering to MyConstructor prototype.If so than why the first(1.) code not referring to MyConstructor prototype? since the property is being added after the instantiation of an object in the second code and the internal prototype of the object receives it ,this means we can change the prototype properties later and still see the effect in the instance .But same definition is not working when prototype properties is replaced in the first code?
Upvotes: 0
Views: 406
Reputation: 151
So, this is one of the reasons I have this article bookmarked:
Constructors Considered Mildly Confusing
Basically, what's happening in the first block of code is that you're overwriting MyConstructor's prototype object with a new object. Whereas, in the second block, you're adding a property to the existing prototype object.
Upvotes: 0
Reputation: 191809
MyConstructor.prototype =
overwrites the entire prototype
object.
The
instanceof
operator tests whether an object has in its prototype chain the prototype property of a constructor
http://jsfiddle.net/ExplosionPIlls/xtqhp/
function MyConstructor () {}
MyConstructor.prototype = {'xyz': 'zyx'};
//true
console.log((new MyConstructor) instanceof MyConstructor);
function MyConstructor2 () {}
var mc2 = new MyConstructor2;
MyConstructor2.prototype = {'xyz': 'zyx'};
//false
console.log(mc2 instanceof MyConstructor2);
By the way, MyConstructor.prototype.protest = {"Maizere"};
is not valid syntax.
Upvotes: 0
Reputation: 11
I might be wrong with this but it looks like when you do:
MyConstructor.prototype = {protest:"maizere"};
You're overriding your prototype with an anonymous object definition, thus when you just add a new property like:
MyConstructor.prototype.protest= {"Maizere"};
Your class keeps its prototype and it works like a charm.
Upvotes: 1