Question

I think its a 5am brain drain, but I'm having trouble with understanding this.

obj = ['a','b'];
alert( obj.prototype ); //returns "undefined"

Why isn't obj.prototype returning function Array(){ } as the prototype? It does reference Array as the constructor.

Was it helpful?

Solution

Because the instance doesn't have a prototype, the class* does.

Possibly you want obj.constructor.prototype or alternatively obj.constructor==Array

* to be more accurate, the constructor has the prototype, but of course in JS functions = classes = constructors

OTHER TIPS

I'm not sure you can access the prototype object from an instance of an object. The following behaviour might help you:

alert(Array); // displays "function Array() { [native code] }"
alert(Array.prototype); // displays ""
alert(['a','b'].constructor); // displays "function Array() { [native code] }"

obj.prototype isn't returning function Array() { ... } as that is the object's constructor.

In your example, obj is an instance of an Array, not the class Array itself.

Another way to understand it is that for example, you can't inherit from an instance of an object (or class), you can only inherit from the object (or class) itself, which in your example it means that you could inherit from the Array object, but not from a direct instance of the Array object such as obj.

According to the ECMA spec, an object's prototype link isn't visible, but most modern browsers (firefox, safari, chrome) let you see it via the __proto__ property, so try:

obj = ['a','b'];
alert( obj.__proto__ );

An object also has the `constructor' property set on construction, so you can try:

obj = ['a','b'];
alert( obj.constructor.prototype );

However, obj.constructor can be changed after an object's contruction, as can obj.constructor.prototype, without changing the actual prototype pointer of obj.

Not really my cup of tea, but does this way of defining it make "obj" an array? Tried

obj = new Array();
obj[0] = "a";
obj[1] = "b";

?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top