开发者

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

开发者 https://www.devze.com 2023-02-19 05:18 出处:网络
I have JavaScript variable as a literal: var global = { getTime : function() { var currentDate = new Date();

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( gl开发者_开发问答obal.doSomething("element_id") );


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

global.doSomething = doSomething;

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


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

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

var global2 = {
    doSomething: that
};

$.extend(global, global2);


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


global.doSomething = function(param){

or

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

精彩评论

暂无评论...
验证码 换一张
取 消