我需要帮助访问对象的属性

时间:2014-01-19 19:41:21

标签: javascript

我在函数属性中有一个对象,我不知道如何访问这些对象属性,更改它们,添加它或从对象中删除它们:

function Example(test) {
    test={};
    test.firstTry='One';
    test.secondTry='Two'; 
    console.log(test);
}
x=new Example("I don't know where to go from here, I want to access test.firstTry and test.secondTry");

4 个答案:

答案 0 :(得分:1)

这些属性是对象的成员,该对象仅在函数内的局部变量中可用。除非您修改功能,否则无法在函数外部访问它们。

您可以将变量公开为对象属性。

this.test = test;

然后

x.test.firstTry;

答案 1 :(得分:1)

如果您使用new关键字,则应使用this

function Example() {
    this.firstTry  = 'One';
    this.secondTry = 'Two';
}

var x = new Example();
console.log(x);

输出:Example {firstTry: "One", secondTry: "Two"}

您也可以返回一个对象:

function Example() {
    var test = {};
    test.firstTry  = 'One';
    test.secondTry = 'Two';
    return test;
}

var x = Example();
console.log(x);

输出:Object {firstTry: "One", secondTry: "Two"}

答案 2 :(得分:1)

要使test对象上的Example属性在构造函数中使用this

 function Example(test){
    this.test={};
    this.test.firstTry='One';
    this.test.secondTry='Two'; 
 }

var x = new Example({});
console.log(x.test.firstTry);

答案 3 :(得分:0)

http://jsfiddle.net/kukiwon/fFzWh/。你忘了添加一个return语句。

function Example(test){
    test={};
    test.firstTry='One';
    test.secondTry='Two'; 
    return test;
}

var x=new Example("I don't know where to go from here, I want to access test.firstTry and test.secondTry");
alert(x.firstTry);
alert(x.secondTry);
相关问题