![](/img/trans.png)
[英]Vue.js 2 + Typescript - global variables becomes undefined after build
[英]Typescript global variables becoming undefined after function call
在我的代碼中,我有兩個全局變量定義為
constructor() {
this.map = new Map();
this.player = new Player([], "");
}
我可以通過程序正常訪問這些變量,但是當我調用函數之一this.handleInput(Command.GO, "north");
在Command.GO轉換為“ GO”而“ north”是一個方向的地方,我所有的全局變量都變得不確定。 在handleInput方法中,
private handleInput(cmd:Command, arg:string):boolean {
console.log("Handling", cmd, "with argument '"+arg+"'");
if (cmd === "GO") {
console.log(`You go ${arg}`);
this.player.setCurrentLocation(this.map.getNextLocation(arg).getName());
this.updateGame(this.map.getNextLocation(arg));
}
}
我立即收到錯誤,指出this.player和this.map是未定義的,但是在調用該方法之前,它們並不是未定義的! 我不了解TS / JS中關於全局變量的某些信息嗎?
你this
是最有可能涉及到另一個對象取決於如何handleInput
被調用。 在你的contructor()
或者bind
handleInput
到this
或更改handleInput
使用箭頭功能:
constructor() {
this.handleInput = this.handleInput.bind(this);
}
要么:
handleInput = (cmd:Command, arg:string):boolean => {}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.