Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prototype chain can't get Object()?

I read an article which explains what prototype chain is.

It says that if I try to access an object's property but it doesn't have it, javascript engine will try it's .constructor.propotype. If it doesn't have it either then try .construtor.propotype.constructor.propotype. Untill it find the built-in Object().

But I test this:

function a() {}
b = new a();

then:

c = b.constructor.prototype

I get an empty a object.

then:

d = c.constructor.prototype

I get an empty a object.

It loops. No matter how many .constructor.prototype I call, it can't find Object(). What's wrong? Do I misunderstand the prototype chain?

like image 993
Lai Yu-Hsuan Avatar asked Feb 02 '26 11:02

Lai Yu-Hsuan


2 Answers

In JS OOP the constructor and prototype properties are flaky, in that they aren't set for you when you perform inheritance. You are supposed to manually set/alter them to implement inheritance. See, for example, this tutorial.

It looks like the way you're trying to climb the prototype chain (by traversing through .constructor.prototype) never really reaches the Object top-level prototype, since when you have function a(){} the right constructor and prototype properties aren't set on a. I can't even manage to coerce them onto a; in Chrome I get:

> function a(){}
undefined
> a.constructor.prototype
function Empty() {}
> a.constructor.prototype = Object.prototype
Object
> a.constructor.prototype
function Empty() {} // hmmmm, the assignment didn't take...

Of course the runtime doesn't need to do this, since it has a reference to the actual prototype of each object. I.e. the language doesn't do the lookup via .constructor.prototype, it saves the prototype of each instance internally. So you can see how the lookup chain works if instead of .constructor.prototype you use .__proto__:

function a(){}
b = new a();
b.__proto__ === Object.prototype; // false
b.__proto__.__proto__ === Object.prototype; // true since we reached the top of the prototype chain

It is important to note that the property __proto__ has never been standard and in ES5 was standardised in a slightly different manner:

obj.__proto__ === Object.getPrototypeOf(obj);

This renders .__proto__ deprecated.

like image 172
davin Avatar answered Feb 05 '26 02:02

davin


Looks like that I asked a stupid question.

if A is a function:

A.prototype.constructor === A

if A isn't a function:

A.prototype in a normal property.

So (in standard) there is no way to climb up the prototype chain.

like image 34
Lai Yu-Hsuan Avatar answered Feb 05 '26 00:02

Lai Yu-Hsuan