Javascript - Passing An Object Literal As Second Arg To Object.create()
Solution 1:
This happens because according to this reference: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create
Object.create
receives an object with "property descriptors" as second argument, not plain key:value
pairs.
See this blog post: 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 property value. From your 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 itself9 obj2.item // nothing because the descriptor that you passed // for item is incomplete
Solution 2:
In line 1 your object literal is interpreted literally and instantiated as you would generally expect.
Whereas, in line 5, your object literal is interpreted literally, but is passed into the Object.create function where the instantiated object is treated as a "properties object containing property descriptors".
Because the Object.create function expects it's second parameter to follow the "Properties Object" convention, your second parameter (on line 8) is invalid (causing a Type Error in Chrome).
The following snippet may help illustrate:
varPrototypeObj= { item:'xxx' };varPropertiesObj= {
propertyDescriptor1: {
value:"prop1value",
writable:true,
enumerable:true,
configurable:true
},
propertyDescriptor2: {
value:"prop2value",
writable:true,
enumerable:true,
configurable:true
}
};varObj=Object.create(PrototypeObj,PropertiesObj);
These articles go into greater detail: Object.create, Object.defineProperty.
Post a Comment for "Javascript - Passing An Object Literal As Second Arg To Object.create()"