将属于对象的匿名方法作为参数传递给Javascript

时间:2014-09-17 16:55:10

标签: javascript oop

我有一个方法的对象,我想将该方法作为参数传递给另一个函数。但是,该函数必须知道与该方法关联的对象(或者它不能在创建后访问分配给该对象的值)。

有没有办法解决这个问题,而不是将对象/方法作为字符串传递? (不使用: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();
}

2 个答案:

答案 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);
}