[英]Difference between arrow function and bind()
I am little confused about while object missing the reference(context).我对 while object 缺少参考(上下文)感到有点困惑。
In TypeScript (shown here with some dummy parameters for explanatory reasons):在 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(): Functions created from function.bind() always preserve 'this' bind():从 function.bind() 创建的函数始终保留“this”
var x = new SomeClass();
window.setTimeout(x.someMethod.bind(x), 100);//bind will be also manage
the x context(reference).
Question:问题:
bind()
and arrow(a=>a...)
function?什么时候使用bind()
和arrow(a=>a...)
function? In the examples you give there is no difference between using function
and using =>
. 在您提供的示例中,using function
和using =>
没有区别。 That is because you don't reference this
inside the callback function. 那是因为您没有在回调函数中引用this
。
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
. 但是,如果您的回调使用this
那么打字稿编译器将在=>
回调内将调用转换为使用_this
,而不在function
回调内使用_this
,并创建一个本地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: 您得到以下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) { }
;
bind()
does not create an anonymous function, whereas =>
does. bind()
不会创建匿名 function,而=>
会。 (This may or may not matter to you.) (这对你来说可能重要也可能不重要。)
=>
creates lexical bindings for this
and all arguments. Wheras bind()
only creates a lexical binding for this
. =>
为this
和所有 arguments 创建词法绑定。而bind()
只为this
创建词法绑定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.