TypeScript:Lambdas并使用';这';
JavaScript框架通常使用apply()调用回调 然而,TypeScript的箭头符号似乎不允许我访问“this”指针 怎么做的TypeScript:Lambdas并使用';这';,lambda,typescript,this,Lambda,Typescript,This,JavaScript框架通常使用apply()调用回调 然而,TypeScript的箭头符号似乎不允许我访问“this”指针 怎么做的 如果不是,是否有地方否决Lambdas上当前的“this”处理方式?TypeScript在箭头函数中对this的处理符合ES6(阅读:)。由于该规范,它以任何其他方式行事都是不一致的 如果要访问当前函数的此,则可以使用常规函数 例如,更改: function myScope() { var f = () => console.log(this);
如果不是,是否有地方否决Lambdas上当前的“this”处理方式?TypeScript在箭头函数中对
this
的处理符合ES6(阅读:)。由于该规范,它以任何其他方式行事都是不一致的
如果要访问当前函数的此
,则可以使用常规函数
例如,更改:
function myScope() {
var f = () => console.log(this); // |this| is the instance of myScope
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;
}
我懂了。但是,改变Lambda表达式的
这个指针的含义,从而根据函数的声明方式引入不同的行为,这并没有带来清晰性,我相信。相反,它增加了歧义和麻烦。ECMA 262-6是否有讨论此问题的链接?@AxD现在肯定太迟了。ES6定于本月出版()。提示
// 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;
}