I’m struggling with the object literal pattern in JavaScript. I’ve been trying to implement, Rebecca Murphy’s example – with modifications of my own.
Basically I want to be able to do two things
1) If no properties are passed – I want a default property/routine executed
2) If a property along with an array are passed – the respective property/function should executed making use of the passed object
I’m wondering if there’s an easier way to implement this instead of calling a function within a function.
var myArr = ["test1", "test2", "test3"];
var stuffToDo = {
bar: function () {
alert('the value was bar -- yay!');
console.log(myArr);
},
baz: function (myArr) {
alert('boo baz :(');
console.log(myArr);
},
def: function (myArr) {
alert('default');
console.log(myArr);
}
};
function Test(varPass)
{
if (varPass) {
varPass();
} else {
stuffToDo['def']();
}
};
Test(stuffToDo['']);
You don’t need to pass the entire function, just the property. How about:
Another way I could think of is to define the stuffToDo as a test function, then add the object literal as static methods on that function:
Or even (encapsulating the object):
OK, the last one was a bit messy 🙂
javascript, so many design patterns….