在下面的代码中:
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));
}
最佳答案
您应该这样做:
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函数。