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( 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;
精彩评论