JavaScript – 将对象文字作为第二个arg传递给Object.create()

请参阅下面的
JavaScript代码段,问题:

>为什么对象文字{item:{value:“foobar”}}在分配给变量时(如第1行)与作为Object.create()的参数传递(如第5行)时的行为不同?
>第5行和第8行有什么区别 – 也就是为什么第5行是将第二个参数传递给Object.create()而不是第8行(以覆盖委托中的item属性)的正确方法?

代码片段:

 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>

最佳答案 这是因为根据这个参考:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create

Object.create接收一个带有“属性描述符”作为第二个参数的对象,而不是普通键:值对.

有关属性描述符的说明,请参阅此博客文章:http://ejohn.org/blog/ecmascript-5-objects-and-properties/.

属性描述符是描述每个属性的对象,而不仅仅是属性值.从您的代码段:

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
点赞