__proto__

Table of Contents

  1. Syntax
  2. Description
  3. Example

Non-standard

Refers to the prototype of the object, which may be an object or null. This property is an abstraction error, because a property with the same name, but any other value could be defined too. If you only need to retrieve the prototype, please prefer Object.getPrototypeOf instead.

In all likelyhood, __proto__ will be in ECMAScript 6 defined as a de-facto standard (the specification codifies what is already in implementations and what webites in the wild rely on).

Syntax

var proto = obj.__proto__;

Note: this is two underscores, followed by the five characters "proto", followed by two more underscores.

Description

When an object is created, its __proto__ property is set to constructing function's prototype property. For example var fred = new Employee(); will cause fred.__proto__ = Employee.prototype;.

This is used at runtime to look up properties which are not declared in the object directly. E.g. when fred.doSomething() is executed and fred does not contain a doSomething, fred.__proto__ is checked, which points to Employee.prototype, which contains a doSomething, i.e. fred.__proto__.doSomething() is invoked.

Note that __proto__ is a property of the instances, whereas prototype is a property of their constructor functions.

Example

This example demonstrates that the __proto__ property can be changed to point to a different object after initial construction. This change will alter the lookup results for object properties. This example also illustrates that all objects have __proto__, including the objects bound to the prototype property of functions. The object anOnion will have a __proto__ property equal to Plant.prototype; if we write anOnion.foo, then we will lookup foo in the anOnion object first, then in Plant.prototype (the value of anOnion.__proto__), then in Lifeform.prototype (the value of Plant.prototype set by the call to extend()), and finally in Lifeform.__proto__.

function extend(child, supertype) {
   child.prototype.__proto__ = supertype.prototype;
}

extend(Animal, Lifeform);
extend(Plant, Lifeform);

var anOnion = new Plant();

However, this only applies to extensible objects: a non-extensible object's __proto__ property (more generally, the object's prototype) cannot be changed:

var obj = {};
Object.preventExtensions(obj);

obj.__proto__ = {}; // throws a TypeError

Tags (1)

Contributors to this page: ethertank, dbruant, Sevenspade, Johnjbarton, Callek, Joriki, zhurizhe, BenB, Waldo, hdon, stepnem
Last updated by: ethertank,
Last reviewed by: ethertank,