Why create the __proto__property when using Object.create?

Asked

Viewed 233 times

6

I just asked that question How to clone an object in javascript?

And another question came to me. When I create an object from another with Object.create the attribute is added to the new object __proto__ containing the content the object passed by argument of create.

Thus:

function writeObject(obj)
{
    document.write(JSON.stringify(obj));
}

a = {nome: 'wallace'}

b = Object.create(a);

writeObject(a);
writeObject(b);
writeObject(b.__proto__);

What does that mean __proto__?

2 answers

7


The __proto__ is the prototype of the object (unlike .prototype of a function, which is not a prototype of it, but of the object it creates when invoked as a constructor).

Only that __proto__ was a property nonstandard until recently (even if available in all implementations I know), and so should not be used. Nothing guarantees that it exists in its implementation (think about the future!). The fact is that in Javascript, up to ES5, there is no way to change the prototype of an existing object without using __proto__. That’s what it’s for, and it should be used very carefully for performance reasons.

In ES6 (ECMA-2015 onwards), __proto__ was included in the specification for compatibility purposes, but was already marked as obsolete (deprecated), in favor of Object.setPrototypeOf and Object.getPrototypeOf. But even with standardization, change the prototype on-the-fly continues to be contraindicated for performance reasons.

  • is an Function getter that is only created when an inheritance is made? vi in the documentation that should use Object.getPrototypeOf instead of ___proto___ in case it is clear to access the values...

  • I don’t know how it is implemented by engines, but it behaves like getter and Setter. In ES5 you can use Object.getPrototypeOf for the getter function, but for Setter has no alternative.

  • 1

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/setPrototypeOf but clear only on ES6

  • Cool, I wasn’t sure if that method was past the Drafts for the final version, I’m glad.

  • In the MDN also says that the property __proto__ is standardized from ES6.0 to ES7.

  • @Matheus I updated the reply, thank you

Show 1 more comment

4

The first parameter of this method Object.create is exactly the object that must be the prototype for the creation of the new object. Hence this parameter is called proto (see page of the MDN) and accessible via __proto__, that is, the reference of the object passed as an argument to the Object.create to create the new object.

var original = {};
var novo = Object.create(original);

console.log(original == novo); // false
console.log(original == novo.__proto__); // true

Browser other questions tagged

You are not signed in. Login or sign up in order to post.