2014-09-02 82 views
0

以下3種方法是我通過哪些屬性可以添加到對象中的。向javascript對象添加屬性的不同方法

> collection = {key0: 'value0'} 
{ key0: 'value0' } 

> collection.key1 = 'value1'; 
'value1' 

> collection['key2'] = 'value2'; 
'value2' 

> collection 
{ key0: 'value0', 
    key1: 'value1', 
    key2: 'value2' } 

是否還有其他方法可用於將屬性添加到對象中。

3種方法都做完全相同的工作嗎?

+1

在第一種情況下,您並不真正添加屬性。您正在替換包含一個包含一個屬性的對象的任何「集合」。這與「添加」一個屬性到一個已經存在的對象是不一樣的。 – 2014-09-02 14:46:41

+1

你需要閱讀:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects – CodingIntrigue 2014-09-02 14:46:43

+0

'Object.defineProperty'和'Object.defineProperties'。請注意,'obj.foo'只是'obj ['foo']'的語法糖。 – 2014-09-02 14:53:03

回答

1

這裏有一個重要的區別:第一個例子創建了一個新的對象(這稱爲「對象字面量」),另外兩個更改一個已經存在的對象

第二個和第三個例子改變以同樣的方式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 
1

第一個語句定義了一個新對象與一個名爲key0的房產。

第二條語句爲對象的屬性key1分配一個值。由於該對象沒有名爲key1的屬性,因此該屬性已創建。

第三種說法與第二種說法相同。的主要原因使用括號符號,而不是點表示法是:

  • 性能有特殊字符,例如,collection["foo-bar"]指稱爲foo-bar屬性,但collection.foo-bar執行對collection.foobar減法運算。

  • 變量屬性名稱,例如,可以執行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" 
相關問題