第一个语句定义了一个新对象与一个名为key0
的房产。
第二条语句为对象的属性key1
分配一个值。由于该对象没有名为key1
的属性,因此该属性已创建。
第三种说法与第二种说法相同。的主要原因使用括号符号,而不是点表示法是:
唯一的其他方式来定义属性是与Object.defineProperty
(以及多个变体Object.defineProperties
)。这使您可以定义以特殊方式运行的属性。
Object.defineProperty(collection, "key3", {
enumerable: false, // property will not show up in for-in loops
configurable: false, // property cannot be changed
set: function(val) {
alert("we tried to set key3 to " + val);
},
get: function() {
alert("this code runs when we get collection.key3");
return "value3";
}
});
collection.key3 = 6; // alerts "we tried to set key3 to 6"
collection.key3; // alerts "this code runs when we get collection.key3"
// and returns the string "value3"
在第一种情况下,您并不真正添加属性。您正在替换包含一个包含一个属性的对象的任何“集合”。这与“添加”一个属性到一个已经存在的对象是不一样的。 – 2014-09-02 14:46:41
你需要阅读:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects – CodingIntrigue 2014-09-02 14:46:43
'Object.defineProperty'和'Object.defineProperties'。请注意,'obj.foo'只是'obj ['foo']'的语法糖。 – 2014-09-02 14:53:03