转换后,TypeScript会不断更改“this”引用

时间:2018-01-28 14:18:47

标签: typescript

我试图运行以下代码段:

interface IPerson{
  firstName:string,
  lastName:string,
  age:number,
  fullName:()=>string
}

var person:IPerson = {    
  firstName: "Tom",
  lastName: "Hal",
  age: 25,    
  fullName: ():string=>{return this.firstName + ' ' + this.lastName}
}

console.log(person.fullName());
console.log(person.age);

我发现tsc转换器正在更改此引用,并且第一个console.log语句的结果未定义,这是因为转换后的代码如下:

var _this = this;
var person = {
    firstName: "Tom",
    lastName: "Hal",
    age: 25,
    fullName: function () { return _this.firstName + ' ' + _this.lastName; }
};
console.log(person.fullName());
console.log(person.age);

“此”引用已更改,我如何才能阻止此行为?

1 个答案:

答案 0 :(得分:4)

将箭头功能更改为常规功能

function():string {return this.firstName + ' ' + this.lastName}

这是预期的行为,TypeScript在针对ES5-时会这样做。因为这正是您将在ES6 +上运行代码的行为。

另一种选择是使用method definitions,您可以像这样写

fullName(): string { return this.firstName + ' ' + this.lastName; }