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

徘徊边缘 提交于 2019-11-30 21:59:36

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 itself

9 obj2.item  // nothing because the descriptor that you passed 
             // for item is incomplete
  1. 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".

  2. 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:

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 go into greater detail: Object.create, Object.defineProperty.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!