我在函数属性中有一个对象,我不知道如何访问这些对象属性,更改它们,添加它或从对象中删除它们:
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");
答案 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);