我如何传递一个对象的方法作为参数没有对象

How do I pass an objects method as parameter without the object

本文关键字:参数 对象 方法 何传递 一个对象      更新时间:2023-09-26

那么,我有一种情况,我需要调用我的对象的一个方法,但在我调用它的时候,对象和被调用的方法都可能不同。

var myCallback = "nameOfMethod"; //this can change throughout
function myObj(){
    this.method1 = function(){//code};
    this.method2 = function(){//more code};
}
var o1 = new myObj();
var o2 = new myObj();
//this is what i'm not sure how to do, but effectively...
//where myCallback could be method1 or method2
//and someObject could be o1 or o2 (for example)
doSomething(someObject,myCallback);
function doSomething(anObj, aMethod){
    anObj.aMethod();
    //or this
    aMethod.call(anObj);
}

编辑:好吧。为了澄清问题。在method1和method2中,它引用了使用this的对象的其他属性,即this。myProperty……但是当我在doSomething中使用anObj[aMethod]()调用方法时,它返回这个。

如果我的对象如下,例如:

function myObj(){
    this.myProperty = "value";
    this.method1 = function(){
        console.log(this.myProperty);
    };
    this.method2 = function(){/* more code */};
}
var o1 = new myObj();
var o2 = new myObj();
//this is what i'm not sure how to do, but effectively...
//where myCallback could be method1 or method2
//and someObject could be o1 or o2 (for example)
doSomething(someObject,myCallback);
function doSomething(anObj, aMethod){
    anObj[aMethod]();
}

正确的调用方法是

anObj[aMethod]();

你的问题是,aMethod是一个属性的名称,而不是一个函数本身。anObj[aMethod]通过读取对象的属性将名称转换为函数。

也就是说,在JavaScript中,当您可以直接传递函数时,将回调作为两个单独的值传递是不太常见的。