“__proto__” in JavaScript

This post is about the “__proto__” property name in JavaScript.

There are two types of “__proto__” in JavaScript:

(1) Directly used as the property name in object initialization, for example:

{ __proto__: {a: 1} }

Note that the property can be surrounded with quotes, and the value must be null or an object. This usage of “__proto__” can be regarded as a special syntax.

(2) Object.prototype.__proto__

This usage is deprecated. In current Node.js implementation, “__proto__” is a getter and setter in Object.prototype. For example, the expression a.__proto__ is equivalent to the following code:

var _get = Object.getOwnPropertyDescriptor(Object.prototype, '__proto__').get;

_get.call(a);

And the expression a.__proto__ = b is equivalent to the following code:

var _set = Object.getOwnPropertyDescriptor(Object.prototype, '__proto__').set;

_set.call(a, b);

If an object is created by Object.create(null), or its prototype is set to null after creation, it cannot access “__proto__”.

For example, at first:

var a = {};

We then set the prototype of a to null:

a.__proto__ = null

At this time, the prototype of a is actually null. However, if we attempt to access the property “__proto__” of a:

a.__proto__

The result is undefined.

And then the code a.__proto__ = b does not call the setter, but directly adds a property named “__proto__” on a, and the value refers to b.

Comments

Leave a comment