Reputation: 1304
I'm trying to work with javascript objects, but not getting very far. Any ideas why this doesn't work?
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
is empty as the choices array in the Tracking
object are still null. This confuses me.
Upvotes: 0
Views: 93
Reputation: 3304
try like this
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);
Upvotes: 1
Reputation: 19791
The problem is here:
Tracking.prototype.setChoice = function (choice){
this.choices.push[choice];
}
You are reading the choice property off the push method of the choices array which doesn't really do anything - it will read the property and return it, but it will return undefined
and that value is not stored or used anywhere.
You instead should set the choices property on this
:
Tracking.prototype.setChoice = function (choice){
this.choices = choice;
}
Check out the Array.push() method for more examples on using the push method correctly.
Upvotes: 0
Reputation: 78750
You've got a few issues here.
function Tracking(){
var choices = new Array();
}
Should be
function Tracking(){
this.choices = new Array();
}
Then, push is a function, use ()
not []
:
this.choices.push(choice);
Then your test code is passing an entire array to setChoice
when that function looks like it sets one item at a time. So you would push 1 element into the array, which is the entire choices array. You would probably want to call setChoice
for each element rather than once. Though really your setChoice
should be named addChoice
as it adds an element, doesn't set the whole array. I would expect setChoice
to just reassign the entire array. It really just depends what you intended that function to really do.
Upvotes: 1