By passing an array as an argument to the constructor we were able to create a compact but readable function that can take any number of arguments and create getter methods for them all.
function Bag(itemArray) {
for (var i = 0; i < itemArray.length; i++) {
(function(i) {
this["getitem" + i] = function() {
return itemArray[i];
};
}).call(this, i);
}
}
Wouldn't it be better if we could add a little bit of metadata to the values we drop into our Bag?
How can we alter it so it's easy to store names, ages, heights, colours, etc.?
If we replace the itemArray parameter with an itemObject object then we'll be able to label all of our values. We can iterate over the object's properties and create getter methods to access their values.
function Bag(itemObject) {
for (var i in itemObject) {
(function(i) {
this["get" + i] = function() {
return itemObject[i];
};
}).call(this, i);
}
}
var bag = new Bag({name:"Bob", age:34, colour:"blue"});
There's not much more to say here. Our investigations and experiments leading to this point have paved the way for a compact, readable, flexible Bag constructor. As is often the case with JavaScript, there's a lot going on to make it all work. Hopefully, you've got a pretty good grip on the mechanisms in play.