第一個語句定義了一個新對象與一個名爲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