Difference between arrow function and bind()

杀马特。学长 韩版系。学妹 提交于 2019-12-10 12:18:38

问题


I am little confused about while object missing the reference(context).

In TypeScript (shown here with some dummy parameters for explanatory reasons):

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() : Functions created from function.bind() always preserve 'this'

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

Question:

  • What are the performance and differences between them?
  • when to use bind() and arrow(a=>a...) function?

回答1:


In the examples you give there is no difference between using function and using =>. That is because you don't reference this inside the callback function.

However, if your callback uses this the typescript compiler will convert the call to use _this inside the => callbacks but not inside the function callbacks and creates a local var _this = this.

So for this typescript:

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) {};

You get this 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) { }
;


来源:https://stackoverflow.com/questions/46585785/difference-between-arrow-function-and-bind

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!