Reputation: 1819
I want to add a function to some object (in a form of a variable) and execute it when i need too.
How to do this?
Thanks.
Upvotes: 2
Views: 124
Reputation: 96845
Pretty vague, but here you go:
var obj = {};
obj.foo = function() {
return "baz";
};
// code...
obj.foo();
Upvotes: 1
Reputation: 285027
obj.doSomething = function()
{
console.log('done');
}
obj.doSomething();
This won't affect any of obj's existing fields or methods (the obvious exception being if there's already a doSomething
).
Upvotes: 5
Reputation: 888107
var myFunc = function() { ... };
var myObj = { func: myFunc };
myObj.func();
You can also skip the myFunc
temporary variable if you want to.
Upvotes: 5