我有一个方法的对象,我想将该方法作为参数传递给另一个函数。但是,该函数必须知道与该方法关联的对象(或者它不能在创建后访问分配给该对象的值)。
有没有办法解决这个问题,而不是将对象/方法作为字符串传递?
(不使用:window[function_name];
)
function My_Object(name){
this.name = name;
}
My_Object.prototype.My_Method = function(){
alert(this.name);
}
//This is the function that passes the method
function Runner(){
var NewObject = new My_Object('Andre');
test(NewObject.My_Method);//this is where it should break
}
//This is the function that receives and calls the Object's method
function test(func){
func();
}
答案 0 :(得分:2)
使用匿名函数:
//This is the function that passes the method
function Runner(){
var NewObject = new My_Object('Andre');
test(function() {
NewObject.My_Method();
});
}
或将您的方法绑定到NewObject
,如下所示:
//This is the function that passes the method
function Runner(){
var NewObject = new My_Object('Andre');
test(NewObject.My_Method.bind(NewObject));
}
并且如果您以后不再更改test
功能,则可以在Runner
函数中简单地调用要测试的函数:
//This is the function that passes the method
function Runner(){
var NewObject = new My_Object('Andre');
NewObject.My_Method(); // directly call the function
}
答案 1 :(得分:1)
有关执行上下文的评论非常重要:
//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);
}