异步和 typeScript class 方法 - 为什么无法访问 class 属性?
Async and typeScript class method - Why no access to class property?
给定一个简单的 typeScript class:
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
);
或者我可以映射数组并对每个值执行 class 方法:
let myInput = new Greeter("John");
async.map(
myArray,
myInput.thisworks
);
但是我无法映射数组,将每个值传递给class方法,并同时访问class 属性:
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
这是词法问题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)
);
给定一个简单的 typeScript class:
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
);
或者我可以映射数组并对每个值执行 class 方法:
let myInput = new Greeter("John");
async.map(
myArray,
myInput.thisworks
);
但是我无法映射数组,将每个值传递给class方法,并同时访问class 属性:
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
这是词法问题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)
);