2012-02-16 78 views
3

這是很難解釋的,也許是更好的,如果我寫的一些示例代碼:JavaScript對象和傳遞成員函數參數

function A() 
{ 
    this.b = new B(); 

    this.a_value = 456; 

    this.f = function(i) 
    { 
     for(var i = 0; i < this.a_value; ++i) 
      DoStuff(i); 
    } 

    this.b.C(this.f) 
} 

我想傳遞一個函數作爲參數傳遞給B,但是當C嘗試達到a_value它是未定義的。我如何解決它?

我希望我沒有過分簡化我的問題。

回答

1

問題是this沒有綁定到JavaScript中的任何固定值。您可以使用閉合來解決這個問題,而且它可能在這種情況下,最好的辦法:

function A() 
{ 
    var that = this; 

    this.b = new B(); 

    this.a_value = 456; 

    this.f = function(i) 
    { 
     for(var i = 0; i < that.a_value; ++i) 
      DoStuff(i); 
    } 

    this.b.C(this.f); 
} 
2

您CA傳遞this.f運作c,但正確地調用它,你也需要傳遞的this像值此:

function A() 
{ 
    this.b = new B(); 

    this.a_value = 456; 

    this.f = function(i) 
    { 
     for(var i = 0; i < this.a_value; ++i) 
      DoStuff(i); 
    } 

    this.b.C(this.f, this) // <== pass "this" here 
} 

And, then in `this.b.c`: 

...b.c = function(fn, context) { 
    fn.call(context);  // <== use .call() here to apply the right this value 
} 
1

現在(或自2015年顯然),也可以在功能結合到對象實例如圖in this answer

this.b.C(this.f.bind(this)); 

通過的解釋道:

var fn = myObject.myFunction.bind(myObject); 

// The following two function calls are now equivalent 
fn(123); 
myObject.myFunction(123); 
0

另一個用箭頭功能實現同樣的事情的方式。由於箭頭函數不綁定this它將保留函數定義時所具有的值。

function A() 
{ 
    this.b = new B(); 

    this.a_value = 456; 

    this.f = i => 
    { 
     for(var i = 0; i < this.a_value; ++i) 
      DoStuff(i); 
    } 

    this.b.C(this.f) 
} 
相關問題