箭头函数和 bind() 的区别
Difference between arrow function and bind()
我对 while object 缺少引用(上下文)有点困惑。
在 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()
和 arrow(a=>a...)
函数?
在您给出的示例中,使用 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) { }
;
我对 while object 缺少引用(上下文)有点困惑。
在 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()
和arrow(a=>a...)
函数?
在您给出的示例中,使用 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) { }
;