Search code examples
javascriptobject-literal

Object Literal Calling Default Property


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['']);

Solution

  • You don’t need to pass the entire function, just the property. How about:

    function Test(prop, arg) {
        ( stuffToDo[prop] || stuffToDo.def )( arg );
    };
    
    Test('whatever', myArr);
    

    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:

    var stuffToDo = function(prop, arg) {
        ( stuffToDo[prop] || stuffToDo.def )( arg );
    }
    
    stuffToDo.bar = function( arr ) { alert('bar'); }
    stuffToDo.def = function() { alert('default'); }
    
    stuffToDo('bar');
    

    Or even (encapsulating the object):

    var stuffToDo = function( prop, arg ) {
        ({
            bar: function(arr) { 
                alert(arr[0]);
            },
            baz: function() {
                alert('baz');
            }
        }[prop] || function() { 
            alert('default');
        })( arg );
    }
    
    stuffToDo('bar', [1,2,3]);​
    stuffToDo('404'); // default
    

    OK, the last one was a bit messy :)

    javascript, so many design patterns....