The default behavior for Object.create ()

I am trying to understand how object creation and the corresponding prototype for an object created using Object.create() . I have the following code:

 var obj = Object.create({name: "someValue"}); console.log(Object.getPrototypeOf(obj)); // => Object{name: "someValue"} console.log(obj.constructor.prototype); // => Object{} // check if obj inherits from Object.prototype Object.prototype.isPrototypeOf(obj); // => true 

Is it correct to say that the last line of code returns true, since the {name: "someValue"} object itself inherits from Object.prototype? Is there a better explanation for this?

+4
source share
1 answer

The Object.prototype.isPrototypeOf specification states that isPrototypeOf checks the chain, not just the parent:

Repeat

  • Let V be the value of the [[Prototype]] internal property of V.

  • if V is zero, return false

  • If O and V refer to the same object, return true.

Your statement is absolutely correct. The created prototype chain has the format:

 obj => Object {name:"someValue"} => Object {} => null / \ | \ -- This guy is Object.prototype 

You can test it using code by creating an object using Object.create and passing null as an argument.

 var obj = Object.create(null); Object.prototype.isPrototypeOf(obj); //false 

Here, since we are passing null , not an object, it itself does not have Object.prototype as a prototype, so we get false .

+2
source

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


All Articles