JS: Object.prototype.__proto__

By Xah Lee. Date: . Last updated: .
obj.__proto__
Return the parent of obj.
  • 🛑 WARNING: use of the property "__proto__" may fail if the object does not have a parent, or if in the parent chain some object has a property string key "__proto__".
  • 🛑 WARNING: not supported in deno nor TypeScript

💡 TIP: Object.prototype.__proto__ is not standard part of JS. It was invented by Firefox browser in 2000s, then supported by all browsers, and JS2015 spec standardize the behavior, but not part of the JavaScript language. It is not supported in some JavaScript implementations. It's not supported in TypeScript nor Deno, as of 2022-07-11

💡 TIP: better use Reflect.getPrototypeOf and Reflect.setPrototypeOf .

// get a obj's parent using __proto__
console.log(
  [4, 6].__proto__ === Array.prototype,
);
obj.__proto__ = parentX
Set the parent of obj to parentX.
Object.prototype.__proto__ is both a getter and a setter property. [see Getter Setter Properties]
// set a obj's parent using __proto__
const e1 = {};
const e2 = {};
e2.__proto__ = e1;
console.log(Reflect.getPrototypeOf(e2) === e1);
const aa = [4, 6];
function FF() {}
aa.__proto__ = FF;
console.log(Reflect.getPrototypeOf(aa) === FF);

Example of __proto__ Failure

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

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

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

Here is 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);

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

// 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__"

JavaScript, Get Set Prototype

BUY ΣJS JavaScript in Depth