Reputation: 513
I want to make a sort of "shopping list" in JS. I'm having trouble accessing the object with the argument of a function.
shopList = {
create: function createList(listName) {
listName = {};
listName["Banana"] = 2
},
output: function output(listName) {
console.log(listName)
},
};
shopList.create('list')
shopList.output('list')
When I run shopList.output 'list' is returned. How do I access the object over the argument? Hope this isn't a duplicate, been googling for hours now and didn't make any progress.
Upvotes: 1
Views: 62
Reputation: 193261
If you want to be able to configure lists with dynamic names then you need to use bracket notation to create lists within this
object. Like this:
var shopList = {
create: function createList(listName) {
this[listName] = {};
this[listName]["Banana"] = 2
},
output: function output(listName) {
return this[listName];
}
};
shopList.create('list');
console.log(shopList.output('list'));
However, as pointed by @armchairdj in comments, it's better to create a container dedicated property to hold lists:
var shopList = {
lists: {},
create: function createList(listName) {
this.lists[listName] = {};
this.lists[listName]["Banana"] = 2
},
output: function output(listName) {
return this.lists[listName];
}
};
Upvotes: 5
Reputation: 1070
If you want to avoid clobbering the methods of your showList object by naively adding arbitrary, user-supplied keys, you should create an internal namespace for your lists.
var shopList = {
lists: {},
create: function (listName) {
this.lists[listName] = this.lists[listName] || {};
this.lists[listName].Banana = 2;
},
output: function (listName) {
var list = this.lists[listName];
if (!list) {
return console.log('No list named ' + listName + ' found.');
}
console.log(list)
}
};
shopList.create('output');
shopList.output('output');
shopList.create('foo');
shopList.output('foo');
shopList.output('bar');
Upvotes: 2