Difference between Object.getPrototypeOf and __proto__

I know that the latter is non-standard. But is there a difference between Object.getPrototypeOf vs __proto__ ? I am learning how the prototype chain works in javascript, and would like to be clear in this part.

Thanks.

+6
source share
3 answers

From MDN :

Object.getPrototypeOf () is the standard implementation of the old and deprecated object .__ proto__ property. However, this is a read-only method.

So basically they do the same thing if you read the value, except __proto__ is non-standard. __proto__ also potentially allows you to install a prototype of an existing object, but as a rule, this is not a good idea, so now it will be standard to use the constructor function or Object.create to create an object with a specific prototype. However, the ES6 specification also defines setPrototypeOf for setting up a prototype object, but for performance reasons, it is best to avoid this if not explicitly required.

+12
source

__proto__ was originally hacked only for Mozilla in earlier versions of Mozilla browsers (Firefox prior to 3.5). It was codified in ECMAScript 3.1 only in 2008.

One of the differences is that __proto__ can be changed (for example, poor design), and getPrototypeOf is a read function.

 var parentObject = {"parentKey" : "parentValue"}; var childObject = {"childKey" : "childValue"}; childObject.__proto__ = parentObject; console.log(childObject.parentKey); // parentValue Object.getPrototypeOf(childObject) = {"parentKey" : "newValue"}; // ReferenceError: Invalid left-hand side in assignment 

Another difference is how they handle the unlikely event of a name conflict:

 var myObject = { __proto__ : "conflicts", getPrototypeOf : function () {return "does not conflict"} }; console.log( myObject.getPrototypeOf() ); // "does not conflict" // all objects inherit from Object.prototype, not Object, so there is no conflict console.log( Object.getPrototypeOf(myObject) ) // Object {} console.log( myObject.__proto__ ); // Object {}, the value "conflicts" is lost 
+6
source

Proxy treats <__ proto __> as get :

 _ = new Proxy({}, { get:z=>console.log('a'), getPrototypeOf:z=>console.log('b'), }); _.__proto__/*a*/ 

- & <getPrototypeOf> as getPrototypeOf :

 _ = new Proxy({}, { get:z=>console.log('a'), getPrototypeOf:z=>console.log('b'), }); Object.getPrototypeOf(_)/*b*/ 
0
source

Source: https://habr.com/ru/post/949882/


All Articles