Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript prototyping: why doesn't this work?

Tags:

javascript

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?


2 Answers

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

like image 124
manji Avatar answered Apr 03 '26 22:04

manji


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);
like image 38
Justin Johnson Avatar answered Apr 03 '26 20:04

Justin Johnson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!