[英]JavaScript function execution in object
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. 如果需要,您还可以跳过myFunc
临时变量。
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
). 这不会影响任何obj的现有字段或方法(显而易见的例外是,如果已经存在doSomething
)。
Pretty vague, but here you go: 很模糊,但你走了:
var obj = {};
obj.foo = function() {
return "baz";
};
// code...
obj.foo();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.