2013-07-31 33 views
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); 
} 
+1

你的問題是什麼? – Jackson

+0

我想從類傳遞函數,並調用它,而不是傳遞類對象,然後調用該函數 – Sakib

+0

FunctionThatTakesFunction(this.someClassVar.bind(this)); – dandavis

回答

1

下面是傳遞一個函數到另一個函數的一些例子:(小提琴這裏:http://jsfiddle.net/FvyUQ/4/

function Cat() { 
    this.myMeow = 'Mrrow'; 

    this.scratch = function() { 
    console.log('Scritchey-scratch.'); 
    } 
} 

Cat.prototype.meow = function() { 
    console.log(this.myMeow); 
} 

Cat.prototype.jump = function() { 
    console.log('The cat jumped and said ' + this.myMeow + '!'); 
} 

function test(fn) { 
    fn(); 
} 

function callPrototype(fn, context) { 
    fn.call(context); 
} 

var myCat = new Cat(); 

test(myCat.scratch); 
test(myCat.meow); 
test(myCat.jump); 
test(Cat.prototype.jump); 
callPrototype(Cat.prototype.jump, myCat); 
相關問題