箭头函数和bind()之间的区别 [英] Difference between arrow function and bind()
问题描述
当对象缺少引用(上下文)时,我很困惑。
I am little confused about while object missing the reference(context).
在TypeScript中(出于解释原因,此处显示了一些虚拟参数):
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():从function.bind()创建的函数始终保留'this'
var x = new SomeClass();
window.setTimeout(x.someMethod.bind(x), 100);//bind will be also manage
the x context(reference).
问题:
- 它们之间的性能和差异是什么?
- 何时使用
bind()
和arrow(a => a ...)
功能?
- What are the performance and differences between them?
- when to use
bind()
andarrow(a=>a...)
function?
推荐答案
在您给出的示例中,使用没有区别功能
并使用 =>
。那是因为你没有在回调函数中引用这个
。
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.
但是,如果你的回调使用这个
typescript编译器会将调用转换为 => $ c中使用
_this
$ c>回调但不在函数
回调中,并创建一个本地 var _this = 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
.
因此对于这个打字稿:
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:
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) { }
;
这篇关于箭头函数和bind()之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!