Javascript 箭头函数和bind()之间的区别
当对象缺少引用(上下文)时,我有点困惑 在TypeScript中(出于解释原因,此处显示了一些伪参数): 胖箭头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));/
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有什么关系?这就是你需要的,简单的谷歌搜索有助于不直接针对你的问题,但在这种情况下值得一读(双关语)