JS: Object.prototype.__proto__

By Xah Lee. Date: . Last updated: .

Object.prototype.__proto__ is both a getter and a setter property. [see JS: Getter/Setter Properties]

You can use it to get or set a object's parent object, like this:

const e1 = {};
const e2 = {};
e2.__proto__ = e1;

console.log ( Reflect.getPrototypeOf ( e2 ) === e1 ); // true

However, if the object does not have a parent (e.g. parent is null), or if in the parent chain some object has a property string key "__proto__", then it'll fail.

Use Reflect.getPrototypeOf and Reflect.setPrototypeOf instead.

[see JS: Get/Set Prototype]

[see JS: Reflect.getPrototypeOf]

[see JS: Reflect.setPrototypeOf]

Get Prototype Example

const arr = [4,6];

console.log (
 Object.getPrototypeOf (arr)  === arr.__proto__
); // true

console.log (
 Object.getPrototypeOf (arr)  === arr["__proto__"]
); // true

Set Prototype Example

const aa = [4,6];

function FF () { }

// set a object's parent
console.log(
    aa.__proto__ = FF
); // [Function: FF]

console.log (
    Object.getPrototypeOf ( aa ) === FF
 ); // true

__proto__ Fail Example

// create a object with no parent
const bb = Object.create (null);

// find out what's the parent
console.log ( bb.__proto__ === undefined); // true
// wrong

console.log ( Reflect.getPrototypeOf ( bb ) === null ); // true
// correct

Here's another example, where in the parent chain a object contains a string key "__proto__".

// create a object with string key __proto__
const bb = {["__proto__"]:3};

// it has a string key __proto__
console.log ( Reflect.ownKeys ( bb ) ); // [ '__proto__' ]

// key value is 3
// this shows __proto__ failed
console.log ( bb.__proto__ === 3); // true

// Reflect.getPrototypeOf works
console.log ( Reflect.getPrototypeOf ( bb ) === Object.prototype ); // true

// 2018-07-19 thanks to Dr. Axel Rauschmayer of 2ality http://2ality.com/2015/09/proto-es6.html for ways to create a string key property "__proto__"

Reference

ECMAScript® 2016 Language Specification#sec-additional-properties-of-the-object.prototype-object

JS Object Property

  1. Property Overview
  2. Property Key
  3. Dot vs Bracket Notation
  4. Create/Delete Property
  5. Get/Set Property
  6. Check Property Existence
  7. Access Property
  8. List Properties
  9. Property Attributes
  10. Getter/Setter
  11. Property Descriptor
  12. Symbol

JS Object and Inheritance

  1. Object Overview
  2. Object Type
  3. Prototype and Inheritance
  4. Create Object
  5. Object Literal Expression
  6. Create Object with Parent X
  7. Get/Set Prototype
  8. Prevent Adding Property
  9. Determine Type of Object
  10. Clone Object
  11. Test Object Equality
  12. Add Method to Prototype
  13. Object Object
  14. Object.prototype
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Reference
  5. DOM
  6. SVG
  7. Web Dev Blog