如何将对象的方法作为参数传递给Javascript中的另一个函数

Rez*_*eza 0 javascript callback

首先来看看下面的简单代码:

function mySecondFunction(objArray,setFunc)
{
    for (let i = 0; i < objArray.length; i++)
    {
        objArray[i].info.setTop(72);
    }
}

function myFunction()
{
    let myObjArray = [];
    for (let i = 0; i < 10; i++)
    {
    myObjArray.push({
        info:{topVar:0,
          bottomVar:0,
          get top() {return this.topVar;},
          get bottom() {return this.bottomVar;},
          setTop: function(input) {this.topVar = input;},
          setBottom: function(input) {this.bottomVar = input; }
         }
    });
    }
    mySecondFunction(myObjArray); // This works Fine
    mySecondFunction(myObjArray,setTop); // I want something like this!!!
}
Run Code Online (Sandbox Code Playgroud)

如您所见,我想将对象的方法传递给另一个函数.我知道很多可能的解决方案来避免这种情况,但我想知道它是否可能.

Kev*_*ian 5

分离它并作为参数传递.请记住用于call设置this目标值.

function mySecondFunction(objArray, setFunc)
{
    for (let i = 0; i < objArray.length; i++)
    {
        setFunc.call(objArray[i].info, 72); 
        /* explicitly telling that: 
        please set 'this' value in this function to be 'objArray[i].info' when running, 
        allowing, e.g. `this.topVar` in 
        `setTop: function(input) {this.topVar = input;}` 
        to be operating on `objArray[i].info.topVar` */
    }
}

function myFunction()
{
    let myObjArray = [];
    for (let i = 0; i < 10; i++)
    {
    myObjArray.push({
        info:{topVar:0,
          bottomVar:0,
          get top() {return this.topVar;},
          get bottom() {return this.bottomVar;},
          setTop: function(input) {this.topVar = input;},
          setBottom: function(input) {this.bottomVar = input; }
         }
    });
    }
    mySecondFunction(myObjArray, myObjArray[0].info.setTop); 
    /* once detaching the method from the object, 
    (if we are not using arrow functions), 
    we lose 'this' value, meaning we are losing 
    the target of object that we want to operate on */
    
    console.log(myObjArray)
}

myFunction();
Run Code Online (Sandbox Code Playgroud)