Nik Sumeiko
Nik Sumeiko

Reputation: 8721

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") );

Upvotes: 2

Views: 6092

Answers (3)

Roman
Roman

Reputation: 276

var global = {
    dothis: function() {
        alert('this');
    }
}

var that = function() {
    alert('that');
};

var global2 = {
    doSomething: that
};

$.extend(global, global2);


$('#test').click(function() {
    global.doSomething();
});

Upvotes: 4

Thor Jacobsen
Thor Jacobsen

Reputation: 8851

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

global.doSomething = doSomething;

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

Upvotes: 4

Quentin
Quentin

Reputation: 943832

global.doSomething = function(param){

or

var doSomething = function(param){ ...
global.doSomething = doSomething;

Upvotes: 0

Related Questions