将参数传递给作为参数

时间:2017-08-17 18:29:35

标签: javascript

在以下代码中:

makeComponent: function(componentBuilder, myLib) {
  componentBuilder.build(function(cmpDefinition, status){
    if (status === 'OK') {
      myLib.doSomething(cmpDefinition);
    }
  });
}

我想将内部回调函数放在一个单独的函数中:

callBackFunc: function(myLib) {
   return function(cmpDefinition, status) {
        if (status === 'OK') {
          myLib.doSomething(cmpDefinition);
        }
   }
}

makeComponent: function(componentBuilder, myLib) {
  var callBackFuncVar = callBackFunc(myLib);
  componentBuilder.build(callBackFuncVar(cmpDefinition, status));
}

此代码不起作用,我需要将makeComponent函数更改为以下内容:

makeComponent: function(componentBuilder, myLib) {
  var callBackFuncVar = callBackFunc(myLib);
  componentBuilder.build(function(cmpDefinition, status) {
       callBackFuncVar(cmpDefinition, status)      
  });
}

为什么直接调用callBackFuncVar并将参数传递给它,如上所述,不起作用?

已修改

如果我这样做怎么办:

callBackFunc: function(cmpDefinition, status) {
        var myLib = this.myLib;
        if (status === 'OK') {
          myLib.doSomething(cmpDefinition);
        }
   }

makeComponent: function(componentBuilder, myLib) {
  componentBuilder.build(callBackFunc.bind(this));
}

1 个答案:

答案 0 :(得分:1)

你应该这样做:

callBackFunc: function(myLib) {
   return function(cmpDefinition, status) {
        if (status === 'OK') {
          myLib.doSomething(cmpDefinition);
        }
   }
}

makeComponent: function(componentBuilder, myLib) {
  var callBackFuncVar = callBackFunc(myLib);
  componentBuilder.build(callBackFuncVar);
}

这背后的原因是componentBuilder.build在第一个例子中接收了一个函数,在第二个例子中接收了callBackFuncVar的结果,而不是callBackFuncVar函数。