JavaScript - passing an object literal as a second argument to Object.create ()

Referring to the snippet of JavaScript code below, the questions are:

  • Why does the object literal {item: {value: "foobar"}} behave differently when assigned to a variable (for example, on line 1), and also when passing Object.create () as an argument (for example, on line 5) ?

  • What is the difference between line 5 and line 8 - that is, why line 5 is the right way to pass the second argument to Object.create () rather than line 8 (to override the element property in the delegate)?

Code snippet:

1 var obj = {item: {value: "foobar"}}; 2 console.log(obj.item); // [object Object] 3 console.log(obj.item.value); // foobar 4 var delegate = {item: "xxx"}; 5 var obj1 = Object.create(delegate, {item: {value: "foobar"}}); 6 console.log(obj1.item); // foobar 7 console.log(obj1.item.value); // undefined 8 var obj2 = Object.create(delegate, {item: "bar"}); 9 console.log(obj2.item); // <nothing> 
+4
source share
2 answers

This is because according to this link: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create

Object.create receives an object with property descriptors as the second argument, not simple key:value pairs.

See the description of this blog: http://ejohn.org/blog/ecmascript-5-objects-and-properties/ for a description of property descriptors.

A property descriptor is an object that describes each property, not just the value of the property. From the code snippet:

 2 obj.item // [object Object] since item is the object {value:"foobar¨} 6 obj1.item // foobar, the descriptor says that the value // of item is "foobar" 7 obj1.item.value // undefined since item="foobar", value is part of // the object that describes "item" not item itself 9 obj2.item // nothing because the descriptor that you passed // for item is incomplete 
+2
source
  • On line 1, your object literal is interpreted literally and instantiated, as you usually expected.

    While in line 5, your object literal is interpreted literally, but passed to the Object.create function, where the object instance is considered as a “property object containing property descriptors”.

  • Since the Object.create function expects the second parameter to follow the "Property Object" convention, your second parameter (on line 8) is invalid (causing a type error in Chrome).

The following snippet can help illustrate:

 var PrototypeObj = { item: 'xxx' }; var PropertiesObj = { propertyDescriptor1: { value: "prop1value", writable: true, enumerable: true, configurable: true }, propertyDescriptor2: { value: "prop2value", writable: true, enumerable: true, configurable: true } }; var Obj = Object.create(PrototypeObj, PropertiesObj); 

These articles are discussed in more detail: Object.create , Object.defineProperty .

0
source

All Articles