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

Pass anonymous method belonging to object as an argument- Javascript

本文关键字:方法 参数 -Javascript 属于 对象      更新时间:2023-09-26

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

有没有一种方法可以做到这一点,而不需要将对象/方法作为字符串传递
(不使用除外: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();
}

使用匿名函数

//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
}

关于执行上下文的注释在这里很重要:

//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);
}