将属于对象的匿名方法作为参数传递-Javascript
我有一个带有方法的对象,我想把方法作为参数传递给另一个函数。但是,函数必须知道与方法关联的对象(或者在创建后无法访问分配给对象的值) 有没有一种方法可以避免将对象/方法作为字符串传递?将属于对象的匿名方法作为参数传递-Javascript,javascript,oop,Javascript,Oop,我有一个带有方法的对象,我想把方法作为参数传递给另一个函数。但是,函数必须知道与方法关联的对象(或者在创建后无法访问分配给对象的值) 有没有一种方法可以避免将对象/方法作为字符串传递? (例如不使用:窗口[函数名称];) 关于执行上下文的注释在这里很重要: //This is the function that passes the method function Runner(){ var NewObject = new My_Object('Andre'); test(N
(例如不使用:
窗口[函数名称];
)
关于执行上下文的注释在这里很重要:
//This is the function that passes the method
function Runner(){
var NewObject = new My_Object('Andre');
test(NewObject.My_Method,NewObject);
}
//This is the function that receives and calls the Object's method
function test(func,ctx){
func.apply(ctx || this);
}
使用匿名函数:
//This is the function that passes the method
function Runner(){
var NewObject = new My_Object('Andre');
test(function() {
NewObject.My_Method();
});
}
或者将您的方法绑定到新对象
,如下所示:
//This is the function that passes the method
function Runner(){
var NewObject = new My_Object('Andre');
test(NewObject.My_Method.bind(NewObject));
}
如果以后不更改
测试
函数,可以在运行程序
函数中简单调用要测试的函数:
//This is the function that passes the method
function Runner(){
var NewObject = new My_Object('Andre');
NewObject.My_Method(); // directly call the function
}
如果你粘贴一些代码,向我们展示你想要完成的事情,这会有所帮助。只要把对象本身传递给函数,函数就可以访问它需要的一切。一些代码示例将有助于给出更多特定于上下文的答案。这完全是重复的。我的Google fu让我失望。
test(function(){NewObject.My_Method();})
?。。。或者test(NewObject.My_Method.bind(NewObject))代码>
//This is the function that passes the method
function Runner(){
var NewObject = new My_Object('Andre');
NewObject.My_Method(); // directly call the function
}