我有一个TypeScript类,有一个我打算用作回调的函数:
removeRow(_this:MyClass): void {
...
// 'this' is now the window object
// I must use '_this' to get the class itself
...
}
Run Code Online (Sandbox Code Playgroud)
我将它传递给另一个函数
this.deleteRow(this.removeRow);
Run Code Online (Sandbox Code Playgroud)
反过来调用jQuery Ajax方法,如果成功,则调用这样的回调:
deleteItem(removeRowCallback: (_this:MyClass) => void ): void {
$.ajax(action, {
data: { "id": id },
type: "POST"
})
.done(() => {
removeRowCallback(this);
})
.fail(() => {
alert("There was an error!");
});
}
Run Code Online (Sandbox Code Playgroud)
我可以保留我的类的'this'引用的唯一方法是将其传递给回调,如上所示.它有效,但它是裤子代码.如果我没有像这样连接'this'(抱歉),那么回调方法中对此的任何引用都已恢复为Window对象.因为我一直在使用箭头函数,所以我期望'this'将是类本身,因为它在我班级的其他地方.
任何人都知道如何在TypeScript中传递回调,保留词法范围?
我正在尝试调用TypeScript类的实例方法(在ASP.NET MVC项目中).但是,在运行时我会遇到异常0x800a01b6 - JavaScript runtime error: Object doesn't support property or method 'checkString'.
我在jsfiddle中复制了生成的JavaScript,其中方法似乎有效.
我不是一个真正的JavaScript人,所以非常感谢任何帮助!
到目前为止我尝试过的事情:
Uncaught TypeError: undefined is not a function,FF: TypeError: this.checkString is not a function)这是TypeScript代码:
class FormData {
BlogName: string;
CacheTimeOut: number;
CopyrightHolder: string;
NavBarTitle: string;
MarkdownExtra: boolean;
MarkdownSanitize: boolean;
RatingActive: boolean;
HtmlEditor: boolean;
constructor(blogName: string, cacheTimeOut: number, copyrightHolder: string, navBarTitle: string, markdownExtra: boolean, markdownSanitize: boolean, ratingActive: boolean, htmlEditor: boolean) …Run Code Online (Sandbox Code Playgroud) 因此,我有一个基本的Typescript应用程序,它实际上不会引起任何重大问题,但是看来这里出了点问题,我也不知道是什么。
我的班级确实有这个私有成员minUpdateRate,该成员在GameContainer构造函数中初始化。这似乎进展顺利,因为在GameContainer.start()调用时,该console.log()方法将打印出来1。
但是,当GameContainer.render()调用该方法时,似乎超出了范围之类,log方法undefined在那里输出。
我是TypeScript的新手,对JavaScript也没有那么深入(特别是在范围方面,这对我来说是令人困惑的:/)。但是,我该如何解决呢?
主班:
class TwoDGame extends Game {
public static main(context:CanvasRenderingContext2D) {
var game:Game = new TwoDGame();
var container:GameContainer = new GameContainer(context, game);
container.start();
return game;
}
}
Run Code Online (Sandbox Code Playgroud)
游戏容器类:
class GameContainer {
...
private minUpdateRate:number;
private game:Game;
private time:number;
...
constructor(context:CanvasRenderingContext2D, game:Game) {
...
this.minUpdateRate = 1;
this.game = game;
}
public start() {
...
console.log(this.minUpdateRate);
}
public render() {
var now:number = new …Run Code Online (Sandbox Code Playgroud)