从函数中访问javascript对象

时间:2013-07-18 18:59:53

标签: javascript object javascript-objects

为什么先工作而不是后者? *它只有一个小的区别,在后一种情况下,我使用速记来访问猫对象属性。我读到如果“属性的名称将是一个有效的变量名称 - 当它没有任何空格或符号并且不以数字字符开头时,它应该没有任何区别。”

    //this works 
    var cats = {Spot:true};

    function addCat (name) {   cats[name] = true; }

    addCat("white");

    console.log ("white" in cats);  //true

    console.log (cats.white); //true

    //this doesn't work 
    var cats = {Spot:true};

    function addCat (name) {   cats.name = true; }

    addCat("white");

    console.log ("white" in cats); //false

    console.log (cats.white); //undefined

1 个答案:

答案 0 :(得分:5)

在您的第二个代码中,cats.name不是动态的,因此您无法在函数中获得name的值;但是,您正在设置名为name的属性:

//this works
var cats = {
    Spot: true
};

function addCat (name) {   
    cats.name = true; 
    // use cats[name] like in your first example
}
addCat("white");

console.log(cats); 
/*
{
    Spot: true,
    name: true
}
*/

console.log ("name" in cats); //true
console.log (cats.name); // true