Reputation: 2285
I'm trying to learn the module design pattern and I'm having trouble with scope in a nested method function. Other questions on the topic appear more advanced than what I'm doing. So, in the following code:
var myModule = function(){
var myObject = {
myArray: [], //array of items
addItem: function(arg){
var item = {
type: "example",
value: arg
}
this.myArray.push(item);
}
}
return myObject;
}
The method "addItem" doesn't seem to be adding the object to "myObject.myArray", but rather adding it to itself? Not quite sure. Can anyone give me a hint? Thanks in advance!
Upvotes: 0
Views: 42
Reputation: 421
Stop trying to cheat death. just use prototype.
Something like:
var MyModule = function() {
this.myArray = [];
};
MyModule.prototype.addItem = function(arg) {
var item = {
type : "example",
value : arg
};
this.myArray.push(item);
};
And you would call it like:
var myModule = new MyModule()
myModule.addItem({
better : 'way'
});
Upvotes: 1
Reputation: 3254
This will work as you expect and item will be pushed to the array of the myObject.
var myModule = function(){
var myObject = {
myArray: [], //array of items
addItem: function(arg){
var item = {
type: value,
value: arg
}
myObject.myArray.push(item);
}
}
return myObject;
}
Though your 'value' var is not defined in the addItem function.
Upvotes: 1
Reputation: 17203
'this' is scoped to the addItem() function. You'd need to use
myObject.myArray.push(item);
You'll see a common practice where functions will set 'this' to another variable to reference later on inside of child functions/objects.
var self = this;
or
var $this = this;
Upvotes: 1