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

Javascript 箭头函数和bind()之间的区别,javascript,typescript,arrow-functions,Javascript,Typescript,Arrow Functions,当对象缺少引用(上下文)时,我有点困惑 在TypeScript中(出于解释原因,此处显示了一些伪参数): 胖箭头 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));/

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

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

胖箭头

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()创建的函数始终保留“this”

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

  • 它们之间的性能和区别是什么
  • 何时使用
    bind()
    箭头(a=>a…)
    函数
在您给出的示例中,使用
函数与使用
=>
之间没有区别。这是因为您没有在回调函数中引用

但是,如果您的回调使用
this
,则typescript编译器将在
=>
回调中而不是在
函数
回调中将调用转换为使用
this
,并创建一个本地
变量_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) { }
;

在您给出的示例中,使用
函数
和使用
=>
没有区别。这是因为您没有在回调函数中引用

但是,如果您的回调使用
this
,则typescript编译器将在
=>
回调中而不是在
函数
回调中将调用转换为使用
this
,并创建一个本地
变量_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) { }
;

这与angular有什么关系?这就是你需要的,简单的谷歌搜索有助于不直接针对你的问题,但在这种情况下值得一读(双关语)这与angular有什么关系?这就是你需要的,简单的谷歌搜索有助于不直接针对你的问题,但在这种情况下值得一读(双关语)