2015-05-14 119 views
3

例如说我有使用节点分类这个功能:如何将对象属性作为参数传递?

function example(){ 

var exampleVar = nodes.classfication; 

//below i use exampleVar to do calculations 
. 
. 
. 
. 
} 

但有时会说我想要得到的节点的状态,所以我这样做:

function example(){ 

    var exampleVar = nodes.status; 

    //below i use exampleVar to do calculations 
    . 
    . 
    . 
    . 
    } 

我不想重复代码(在我的代码中)我想要重用的函数中有相当多的代码。所以,根据我想摆脱这种功能的是什么病它传递给函数,像这样:

function example(thisAttribute){ 

    var exampleVar = nodes.thisAttribute; //using the variable passed to the function 

    //below i use exampleVar to do calculations 
    . 
    . 
    . 
    . 
    } 

这是不行的,我怎么去传递一个对象的属性作为参数传递给函数?我尝试过在网上寻找,但我不认为我正在寻找正确的东西,因为我找不到任何帮助。在此先感谢反正:)

+0

相关,潜在的重复:[JavaScript属性访问:点符号与括号(http://stackoverflow.com/questions/4968406/javascript -property-access-dot-notation-vs-brackets) –

回答

5

使用object bracket notation

function example(thisAttribute){ 
    var exampleVar = nodes[thisAttribute]; 
} 
+1

ahh很好,我不知道。非常感谢:D – thatOneGuy

相关问题