最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - How to extend JavaScript literal (object) with a new variable? - Stack Overflow

programmeradmin0浏览0评论

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

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") );
Share Improve this question asked Mar 24, 2011 at 10:16 Nik SumeikoNik Sumeiko 8,7519 gold badges52 silver badges53 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

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

global.doSomething = doSomething;

http://jsfiddle/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)

  1. 暂无评论