3

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?

  • http://stackoverflow.com/questions/383201/relation-between-prototype-and-prototype-in-javascript – Eineki Apr 26 '11 at 18:22

4 Answers4

3

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);
Justin Johnson
  • 30,978
  • 7
  • 65
  • 89
3

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

manji
  • 47,442
  • 5
  • 96
  • 103
1

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);
Austin Taylor
  • 5,437
  • 1
  • 23
  • 29
1

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 :-)

AngusC
  • 628
  • 5
  • 9