我正在尝试使用 javascript 对象,但还没有走得太远。有什么想法为什么这行不通吗?
function Tracking(){
var choices = new Array();
}
Tracking.prototype.getChoice = function (key){
return this.choices[key];
}
Tracking.prototype.setChoice = function (choice){
this.choices.push[choice];
}
function TrackingChoice(key, choice){
this.key = key;
this.choice = choice;
}
......
var tracking = new Tracking();
var choices = new Array();
choices.push(new TrackingChoice("purchase", true));
choices.push(new TrackingChoice("listing", false));
choices.push(new TrackingChoice("offers", false));
choices.push(new TrackingChoice("messages", false));
tracking.setChoice(choices);
var a = tracking.getChoice(0);
var a
为空,因为 Tracking
对象中的选择数组仍然为空。这让我很困惑。
最佳答案
尝试这样
function Tracking(){
this.choices = []; var count = 0;
this.getChoice = function (key){
return this.choices[key];
};
this.setChoice = function (choice){
this.choices[count] = choice;count++;
};
}
function TrackingChoice(key, choice){
this.key = key;
this.choice = choice;
}
var tracking = new Tracking();
var choices = new Array();
tracking.setChoice(new TrackingChoice("purchase", true));
tracking.setChoice(new TrackingChoice("listing", false));
tracking.setChoice(new TrackingChoice("offers", false));
tracking.setChoice(new TrackingChoice("messages", false));
var a = tracking.getChoice(0);
关于javascript 获取和设置属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19873305/