【问题标题】:Async and typeScript class method - Why no access to class property? [duplicate]异步和 typeScript 类方法 - 为什么不能访问类属性? [复制]
【发布时间】:2017-05-31 19:46:08
【问题描述】:

给定一个简单的 typeScript 类:

class Greeter {
  greeting: string;

  constructor(message: string) {
    this.greeting = message;
  }

  greet() {
    return "Hello, " + this.greeting;
  }

  thisworks(input) {
    console.log("I am " + input) ;
  }

  doesNotWork(input) {
    return "Hi " + this.greeting +". I am " + input;
  }   
}

一个数组:

let myArray = ["Joe","William","Jack","Averell"];

还有一个功能:

let myFunction = (name) => {
  let obj = new Greeter(name);
  console.log(obj.greet());
};

我可以映射数组并为每个值执行函数:

async.map(
  myArray,
  myFunction
);

或者我可以映射数组并使用每个值执行一个类方法:

let myInput = new Greeter("John");

async.map(
  myArray,
  myInput.thisworks
);

但我无法映射数组,将每个值传递给类方法,并同时访问类属性:

let myInput = new Greeter("Bill");

async.map(
  myArray,
  myInput.doesNotWork
);

谁能解释一下为什么最后一个例子不起作用?以及如何让它发挥作用?

我预计最后一个示例的结果是:

Hi Bill. I am Joe
Hi Bill. I am William
Hi Bill. I am Jack
Hi Bill. I am Averell

相反,我收到以下错误:

Uncaught TypeError: Cannot read property 'greeting' of undefined

这里是a plunk associated with this question

【问题讨论】:

  • 与每个人都遇到的基本上相同的范围问题。 myInput.doesNotWork 是用 this 调用的,它指的是 myInput 以外的东西。要么将其绑定到正确的上下文,如 myInput.doesNotWork.bind(myInput),要么使用函数调用,如 (item) => myInput.doesNotWork(item)...

标签: javascript asynchronous typescript async.js


【解决方案1】:

这是词法 this 的问题。

解决方案是确保在创建函数或调用函数时绑定this

函数创建时绑定this

class Greeter {
    greeting: string;

    constructor(message: string) {
      this.greeting = message;
    }

    doesNotWork = (input) => {
      console.log("Hi " + this.greeting +". I am " + input);
    }

}

在调用点绑定this

let myInput = new Greeter("Bill");
async.map(
    myArray,
    myInput.doesNotWork.bind(myInput)
);  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-23
    • 1970-01-01
    相关资源
    最近更新 更多