2014-09-02 62 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" 
相关问题