繁体   English   中英

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

[英]How to pass an object's method as a parameter to another function in Javascript

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

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, eg `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(); 

您可以在阵列列表中定位项目编号。 您可以通过迭代和变量来静态(即1-???)或动态地进行。 然后,您可以在其中进行对象属性。 例如:

myObjArray[0].info.setTop

这将定位数组中的第一项。 传递方法时,请务必省略括号( () ),因为您要传递函数引用而不是结果

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM