2017-02-01 72 views
0

不知道問題的標題是否太混亂,但我在這裏。當外部'this'被綁定時訪問當前元素的'this'對象

如果我是這樣的:

var Test = function(){ 
    this.foo = a; 
} 

Test.prototype.init = function() { 
    $(document).on('change', '.form-control', this.myFunction); 
} 

Test.prototype.myFunction = function() { 
    console.log(this.foo); 
    console.log(this); 
} 

我的理解是,在myFunction的打印「」時,將打印進行呼叫的函數的執行環境,在這種情況下,它會打印.on('change'...)的執行上下文。因此,當打印this.foo,因爲它不存在於這種情況下,然後undefined將被打印出來。

爲了解決這個問題,並訪問this.foo,我做了以下內容:

Test.prototype.init = function() { 
    $(document).on('change', '.form-control', (this.myFunction).bind(this)); 
} 

Test.prototype.myFunction = function() { 
    console.log(this.foo); 
    console.log(this); 
} 

我結合「」的函數調用,所以this.foo會被打印出來,這是好的,但我的問題是,在那種情況下,我怎樣才能獲得.on('change'...)的執行上下文?意思是,如何訪問我在綁定之前最初訪問的'這個'?

謝謝

+0

http://stackoverflow.com/questions/80084/in-javascript-why-is-the-this-operator-inconsistent – Snowmonkey

回答

0

而不是綁定,只是使用引用變量。它將保持上下文,仍允許您使用.on的情況下與this

Test.prototype.init = function() { 

    var context = this; 

    $(document).on('change', '.form-control', function() { 
     context.myFunction(); 
     console.log(this); // `this` has context to the onchange 
    }); 
}; 
0

一個綁定功能的this將永遠被綁定到相同的值。這意味着您不再有權訪問「原始」值。

如果您想同時使用this es,則必須使用一個作爲this,另一個作爲參數。或者兩者都作爲論據。

var Test = function(a) { 
 
    this.foo = a; 
 
    this.init(); 
 
} 
 

 
Test.prototype.init = function() { 
 
    // Set `this` to the calling test object, and window 
 
    // (which would be the original context in this case) 
 
    // as first parameter of `myFunction`. Swap the arguments 
 
    // if you wish to use them the other way around. 
 
    window.setTimeout(this.myFunction.bind(this, window), 500); 
 
}; 
 

 
Test.prototype.myFunction = function(that) { 
 
    console.log(this.foo); 
 
    console.log(that.foo); 
 
}; 
 

 
new Test(5);

順便說一句,ES6 arrow functions保持他們在規定的環境中,這意味着this將指向您的測試對象。

Test.prototype.init = function() { 
    window.setTimeout(() => this.myFunction(window), 500); 
}; 
相關問題