JavaScript框架通常使用apply()调用回调。
但是TypeScript的箭头符号似乎不允许我访问'this'指针。
如何完成?
如果不是,是否有地方可以对Lambda上的当前'this'处理进行投票?
TypeScript对箭头功能中的this
的处理与ES6一致(读取:Arrow Functions)。由于该规范,它以任何其他方式起作用都将是不一致的。
如果要访问当前功能的this
,则可以使用常规功能。
例如,更改:
function myScope() {
var f = () => console.log(this); // |this| is the instance of myScope
f.call({});
}
new myScope();
收件人:
function myScope() {
var f = function() { console.log(this); } // |this| is {}
f.call({});
}
new myScope();
使Lambda函数与关键字this一起使用的一种方法是将其放在类中。
在下面的示例中,函数employee2将不会编译:
// Using a method defined as a lambda function
class Company{
private id : number
private name : string;
public employee = (id : number, name : string) => {
this.id = id;
this.name = name;
}
}
// Using a function declaration
function employee1(id : number, name : string){
this.id = id;
this.name = name;
}
// Using a lambda function
const employee2 = (id : number, name : string) => {
this.id = id;
this.name = name;
}
// Using a function expression
const employee3 = function(id : number, name : string){
this.id = id;
this.name = name;
}