I'm looking at trying the following code:
var classA = function() {};
classA.prototype = { x: 4, y: 6 };
classA.prototype.prototype = { z: 10 };
var foo = new classA();
alert(foo.z);
Why does the alert come back as undefined? Shouldn't javascript follow the prototype chain to find z?
By default an object prototype is an empty object.
classA.prototype = { x: 4, y: 6 };
classA.prototype.prototype = { z: 10 };
is equivalent to
classA.prototype = { x: 4, y: 6, prototype: { z: 10 }};
you just added a property named prototype to classA
z is a property of the object prototype belonging to classA
alert(foo.prototype.z); will work
I don't believe that you can change the prototype of a prototype or if such a thing even exists. Do this instead
var classA = function() {};
classA.prototype = { x: 4, y: 6 };
classA.prototype.z = 10;
var foo = new classA();
alert(foo.z);
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