2017-10-05 45 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) { } 
; 
相关问题