__proto__

Table of contents

  1. 1. Summary
  2. 2. Syntax
  3. 3. Description
  4. 4. Example
Table of contents
  1. 1. Summary
  2. 2. Syntax
  3. 3. Description
  4. 4. Example

Non-standard

Deprecated

Summary

Refers to the prototype of the object, which may be an object or null (which usually means the object is Object.prototype, which has no prototype).  It is sometimes used to implement prototype-inheritance based property lookup.

This property is deprecated and should not be used in new code: use Object.getPrototypeOf instead.

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)

Edit tags

Attachments (0)

 

Attach file