[英]Different methods of adding properties to javascript object
我遇到了以下3種方法,可以通過這些方法將屬性添加到對象。
> collection = {key0: 'value0'}
{ key0: 'value0' }
> collection.key1 = 'value1';
'value1'
> collection['key2'] = 'value2';
'value2'
> collection
{ key0: 'value0',
key1: 'value1',
key2: 'value2' }
是否存在其他可以將屬性添加到對象的方法。
這三種方法是否都做完全相同的工作?
這里有一個重要的區別:第一個示例創建一個新對象(這稱為“對象文字”),另外兩個更改一個已經存在的對象。
第二個和第三個示例以相同的方式更改collection
對象,不同之處在於無法使用點表示法中的變量屬性名稱:
// Let's say we have an object
var collection = { key0 : "value0" };
// Let's say for some reason we want to use a variable as a property name
var keyName = "key1";
// This won't assign "someValue" to the property "key1" as you would expect
// instead it will assign it to the property "keyName" (the string, not the variable)
collection.keyName = "someValue"; // OOPS
// With bracket notation you can use a variable (or any expression) as a property name
collection[keyName] = "value1"; // Sweet
第一條語句定義了一個具有名為key0
的單個屬性的新對象。
第二條語句為對象的名為key1
的屬性分配一個值。 由於對象沒有自己的名為key1
的屬性,因此將創建該屬性。
第三條語句與第二條語句的作用相同。 使用括號表示法代替點表示法的主要原因是:
具有特殊字符的屬性,例如collection["foo-bar"]
指的是稱為foo-bar
的屬性,但是collection.foo-bar
在collection.foo
和bar
上執行減法運算。
可變屬性名稱,例如,可以執行var propName = "key0"; collection[propName] = ...
var propName = "key0"; collection[propName] = ...
定義屬性的唯一其他方法是使用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"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.