箭头函数和bind()之间的区别

时间:2017-10-05 12:35:22

标签: javascript typescript arrow-functions

当对象缺少引用(上下文)时,我很困惑。

在TypeScript中(出于解释原因,此处显示了一些虚拟参数):

Fat Arrow

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 个答案:

答案 0 :(得分:3)

在您给出的示例中,使用function和使用=>之间没有区别。那是因为你没有在回调函数中引用this

但是,如果你的回调使用this,那么typescript编译器会将调用转换为_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) { }
;