gpt4 book ai didi

javascript - 如何在 TypeScript 中捕获 "this"

转载 作者:搜寻专家 更新时间:2023-10-30 21:31:14 24 4
gpt4 key购买 nike

我什至尝试包装到一个模块中,但仍然未能在所有尝试中捕获“this”。由以下 Typescript 生成的 Javascript 无法解析 this 并且无法返回所需的结果。我该如何解决 TypeScript 中的这个问题?

var secretNumberGame = () => {
var secretNumber: number = 21;
var counter: number = 9;
return {
responses: {
equal: "You are correct! Answer is " + secretNumber,
lower: "Too high!",
higher: "Too low!"
},
guess: (guess: number) => {
counter++;
var key = (guess == secretNumber) ? "equal" : (
(guess < secretNumber ? "higher" : "lower"));
console.log(this.responses[key]);
return counter;
}
}
}
var game = secretNumberGame();
console.log(game.guess(45));
console.log(game.guess(18))
console.log(game.guess(21));

最佳答案

请只使用函数而不是()=>:

var secretNumberGame = () => {
var secretNumber: number = 21;
var counter: number = 9;
return {
responses: {
equal: "You are correct! Answer is " + secretNumber,
lower: "Too high!",
higher: "Too low!"
},
guess: function (guess: number) {
counter++;
var key = (guess == secretNumber) ? "equal" : (
(guess < secretNumber ? "higher" : "lower"));
console.log(this.responses[key]);
return counter;
}
}
}
var game = secretNumberGame();
console.log(game.guess(45));
console.log(game.guess(18))
console.log(game.guess(21));

这里有一些关于粗箭头的文档:http://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html

关于javascript - 如何在 TypeScript 中捕获 "this",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32489926/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com