JavaScript: Object.prototype.__proto__
obj.__proto__
- Return the parent of obj.
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]
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 2020-09-13
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__"
.
Better use Reflect.getPrototypeOf and Reflect.setPrototypeOf .
// set a obj's parent using __proto__ const e1 = {}; const e2 = {}; e2.__proto__ = e1; console.log( Reflect.getPrototypeOf ( e2 ) === e1 ); // true
Get Prototype Example
console.log( Reflect.getPrototypeOf ([4,6]) === [4,6].__proto__ ); // true
Set Prototype Example
const aa = [4,6]; function FF () { } aa.__proto__ = FF console.log( Reflect.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 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); // 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__"