我将类或 var 对象中的函数作为参数传递给另一个函数。从类中接收函数的函数执行该函数。它可以正常工作,但是该类的函数从该类中调用另一个函数。控制台输出类函数中调用的函数未定义的错误。
以下可能会更好地说明
//the class variable in someClass.js
function(params...){
getSomethingInClass: function(){
// return some variable
}
functionThatIsPassed: function(arg){
var theCalledFunction = getSomethingInClass();
//do something with theCalledFunction
}
}
//SOME WHERE ELSE in another function in another file
OtherFunction: function(){
//someClass is a variable being used here
FunctionThatTakesFunction(this.someClassVar.functionThatIsPassed);
}
//FunctionThatTakesFunction is implemented in another file
FunctionThatTakesFunction(callbackFun){
callbackFun(someArg);
}
如果我将其更改为传递整个对象 someClass 对象,则上述方法将起作用。传递对象是不好的编程习惯,因为 FunctionThatTakesFunction 需要知道其参数的功能 例如
//THIS WORKS!
//other stuff is same
//SOME WHERE ELSE in another function in another file
OtherFunction: function(){
//someClass is a variable being used here
FunctionThatTakesFunction(this.someClassVar);
}
//FunctionThatTakesFunction is implemented in another file
FunctionThatTakesFunction(object){
object.functionThatIsPassed(someArg);
}