2017-10-05 47 views
0

對於缺少引用(上下文)的對象,我有點困惑。箭頭函數和bind之間的區別()

在打字稿(與解釋原因,某些虛擬參數如下所示):

var x = new SomeClass();  
someCallback(function(a){x.doSomething(a)});// some time this x object may 
missing the reference (context) of x object 

someCallback(a => x.doSomething(a));// if we using arrow function, then how 
it manage stabling the object context? which is doing same below bind()code. 

bind()的

發箭:從function.bind創建功能()始終保持「這「

var x = new SomeClass(); 
window.setTimeout(x.someMethod.bind(x), 100);//bind will be also manage 
the x context(reference). 

問題:

  • 它們之間的性能和差異是什麼?
  • 何時使用bind()arrow(a=>a...)函數?
+1

這是如何關係到角? – Skeptor

+1

https://stackoverflow.com/questions/22939130/when-should-i-use-arrow-functions-in-ecmascript-6 –

+1

這就是你需要的,簡單的谷歌搜索幫助http://2ality.com/2016/ 02/arrow-functions-vs-bind.html –

回答

3

在你給有使用function和使用=>沒有區別的例子。這是因爲你在回調函數中沒有引用this

但是,如果你的回調使用this的打字稿編譯器將轉換爲使用_this=>回調中,但不是function回調內部呼叫,並創建一個本地var _this = this

因此,對於這個打字稿:

class SomeClass { 
    x: any; 
    foo() { 

    someCallback(function(a:number){this.x.doSomething(a)});// some time may missing the reference (context) of x object 

    someCallback((a:number) => this.x.doSomething(a)); 
    } 
} 
function someCallback(foo: any) {}; 

你得到此javascript:

var SomeClass = (function() { 
    function SomeClass() { 
    } 
    SomeClass.prototype.foo = function() { 
     var _this = this; 
     someCallback(function (a) { this.x.doSomething(a); }); // some time may missing the reference (context) of x object 
     someCallback(function (a) { return _this.x.doSomething(a); }); 
    }; 
    return SomeClass; 
}()); 
function someCallback(foo) { } 
; 
相關問題