Search code examples
javascriptjqueryliteralsjavascript-objectsobject-literal

How to extend JavaScript literal (object) with a new variable?


I have JavaScript variable as a literal:

var global = {
    getTime : function() {
        var currentDate = new Date();
        return currentDate.getTime();
    }
};

And I wish to extend this literals with other different functions, which are going to be created as variables:

var doSomething = function(param){
    $("#" + param).hide();
    return "hidden";
}


How can I extend my literal with a new variable, which holds a function?!
At the end I wish to use this in such a way:

alert( global.doSomething("element_id") );

Solution

  • To extend your global variable with the method doSomething, you should just do this:

    global.doSomething = doSomething;
    

    http://jsfiddle.net/nslr/nADQW/