javascript prototyping: why doesn't this work?
I'm looking at trying the following code:
var classA = function() {};
classA.prototype = { x: 4, y: 6 };
classA.prototype.prototype = { z: 10 };
va开发者_如何学运维r 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);
The prototype of an object is stored in __proto__
. The prototype
property on a class is actually the default prototype for its instances. I found this article to be very helpful.
If you change your code to use __proto__
for the prototype of the prototype, it will behave as you expected.
var classA = function() {};
classA.prototype = { x: 4, y: 6 };
classA.prototype.__proto__ = { z: 10 };
var foo = new classA();
alert(foo.z);
The prototype property comes for free on all functions - in case the function is intended to be used as a constructor (it defines the prototype to be assigned to instances created by that constructor).
You are trying to assign a prototype property to a non-function - which is meaningless. In some browsers The prototype of an object can be get and set by the non standard proto attribute.
There is also a new ECMA standard API for accessing an object's prototype
Object.getPrototypeOf(obj)
but it is not yet supported by all browsers
Edit: just realized I am the author of Austin's link :-)
精彩评论