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

标签 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!!!
}

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

最佳答案

将其分离并作为参数传递。请记住使用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();

关于javascript - 如何在 Javascript 中将对象的方法作为参数传递给另一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49226079/

相关文章:

javascript - AJAX Post 使用 Python 和 javascript 存储 JSON

javascript - JS加密-python解密

javascript - 有没有更好的方法来覆盖 JS ajax 回调?

使用 2 种可能方法之一的 Java 接口(interface)/回调

javascript - 如何一个一个地同时加载和渲染数据

javascript - 如何从回调javascript导出结果

c++ - 使用 GetProcAddress : callback function fails with invalid parameter 从 C++ 调用 Delphi DLL

javascript - 使用 .after() 创建表格但无法访问变量的值来填充单元格

javascript - 如何在 Vue 中动态获取组件 Props

javascript数组在另一个数组中重复