Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between proto link and Object.create

I want to know the difference between __proto__ and Object.create method. Take this example:

var ob1 = {a:1};
var ob2 = Object.create(ob1);

ob2.__proto__ === ob1; // TRUE

This implies Object.create method creates a new object and sets __proto__ link to the object received as parameter. Why don't we directly use __proto__ link instead of using create method ?

like image 277
Sachin Avatar asked Mar 11 '13 13:03

Sachin


2 Answers

__proto__ is nonstandard and won't be supported everywhere. Object.create is part of the official spec and should be supported by every environment going forward.

It also is implemented differently in different places.

From Effective Javascript:

Environments differ for example, on the treatment of objects with a null prototype. In some environments, __proto__ is inherited from Object.prototype, so an object with a null prototype has no special __proto__ property

Moving forward the accepted way to create objects and implement inheritance is the Object.create function, and if you do need to access the prototype, you'll want to use Object.getPrototypeOf These functions are standardized and should work the same in all modern environments

like image 168
Ben McCormick Avatar answered Sep 27 '22 22:09

Ben McCormick


Why don't we directly use proto link instead of using create method ?

Because __proto__ is a non-standard property and therefore not necessarily available in every browser.

However it seemed to be considered for ES.next. More info: MDN - __proto__.

like image 23
Felix Kling Avatar answered Sep 27 '22 22:09

Felix Kling