TypeScript 中的方法 x 粗箭头

Method x fat arrow in TypeScript

有什么区别:

export class Test {

  x: any;

  processData = (data) => {
    console.log("This=",this);
    this.x = data; 
    console.log("Loaded.", data);
  }
}

还有这个:

export class Test {

 x: any;

 processData(data) {
  console.log("This=",this);
  this.x = data; 
  console.log("Loaded.", data);
 }

}

最后一个,代码如下:

 ionViewLoaded() {
   console.log("## ionViewDidLoad");
   this.myApi.getPromise().then(this.processData);
 }

ionViewLoaded() 函数不起作用,因为 processData() 中的 this==null

this 实际上恰好是 === undefined 严格模式下 第二个例子。不同之处在于,所有箭头函数都关闭它们创建范围的词法 this 值。

在你的第一个例子中:

export class Test {

  x: {}; // Please stop using any.

  processData = (data) => {
    console.log("This=", this);
    this.x = data; 
    console.log("Loaded.", data);
  }
}

当您定义实例 属性 时,词法上下文是封闭 class 的 实例 不是 一个原型方法,它的值是一个关闭的箭头函数。

在第二个例子中:

export class Test {

  x: {};// Please stop using any.

  processData(data) {
    console.log("This=", this);
    this.x = data; 
    console.log("Loaded.", data);
  }

}

您正在 class 原型上创建方法。一个方法有一个 动态 作用域的 this 引用,它在被调用时在调用时绑定。

如果您将其称为 object.method()this 将引用 method 内部的 object 用于该调用且仅该调用。

如果你称它为method(),即没有接收对象,如果你运行在严格模式下,那么这将是undefinedmethod 内用于该调用且仅该调用。

如果您不是 运行宁在严格模式下,这将引用全局对象。例如,在浏览器中它将引用 window。这真是太糟了。在严格模式下始终 运行。

代码隐含在 ES 模块和 class 主体内的严格模式下。您可以通过使用 'use strict'; 指令序言开始封闭文件或封闭函数来显式设置严格模式。

这就是您的第二个示例中代码失败的原因,因为 this 未定义。为了将 method 作为回调传递,您需要先 bind 它。 也就是说你会写

ionViewLoaded() {
  console.log("## ionViewDidLoad");
  this.myApi.getPromise().then(this.processData.bind(this));
}

或者,您可以创建一个箭头函数来关闭实例和使用站点的方法,如

ionViewLoaded() {
  console.log("## ionViewDidLoad");
  this.myApi.getPromise().then(data => this.processData(data));
}

或者像第一个例子一样使用绑定到 属性 的箭头函数。

哦,如果评论没有给你提示,请不要用 any 类型注释任何内容。

希望对您有所帮助。