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.
var myFunc = function() { ... };
var myObj = { func: myFunc };
myObj.func();
You can also skip the myFunc
temporary variable if you want to.
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
).
Pretty vague, but here you go:
var obj = {};
obj.foo = function() {
return "baz";
};
// code...
obj.foo();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.