1
我將一個類或var對象中的函數作爲參數傳遞給另一個函數。 從類中取得函數的函數執行該函數。 它會正常工作,但是類的功能會從類中調用另一個函數。 控制檯輸出在類函數中被調用的函數未定義的錯誤。javascript在需要另一個類的對象的類中傳遞一個函數
下可能說明好一點
//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);
}
你的問題是什麼? – Jackson
我想從類傳遞函數,並調用它,而不是傳遞類對象,然後調用該函數 – Sakib
FunctionThatTakesFunction(this.someClassVar.bind(this)); – dandavis