I know this is probably painfully basic, but i am having a tough time wrapping my head around it.

class Main
{
     constructor()
     {
         requestAnimationFrame(this.update);  //fine    
     }

     update(): void
     {
         requestAnimationFrame(this.update);  //error, because this is window
     }

}

It appears to be the case that I need a proxy, so lets say using Jquery

class Main
{
     constructor()
     {
         this.updateProxy = $.proxy(this.update, this);
         requestAnimationFrame(this.updateProxy);  //fine    
     }

     updateProxy: () => void
     update(): void
     {
         requestAnimationFrame(this.updateProxy);  //fine
     }

}

But coming from an Actionscript 3 background, I am not really sure what is happening here. Sorry I am not sure where Javascript begins and TypeScript ends.

updateProxy: () => void

而且,我不相信我做得对.我最不想看到的是,我的大多数类都有一个a()函数,需要用aProxy()来访问它,因为我觉得我要写两次同样的东西?这正常吗?

推荐答案

If you want this captured the TypeScript way of doing this is via arrow functions. To quote Anders:

The this in arrow functions is lexically scoped

以下是我喜欢利用这一点对我有利的方式:

class test{
    // Use arrow functions
    func1=(arg:string)=>{
            return arg+" yeah" + this.prop;
    }
    func2=(arg:number)=>{
            return arg+10 + this.prop;
    }       

    // some property on this
    prop = 10;      
}

View this in the TypeScript Playground

You can see that in the generated JavaScript this is captured outside the function call:

var _this = this;
this.prop = 10;
this.func1 = function (arg) {
    return arg + " yeah" + _this.prop;
};

因此,函数调用中的this值(可以是window)将不会使用.

To learn more: “Understanding this in TypeScript” (4:05) – YouTube

Jquery相关问答推荐

我在自定义 WordPress 插件中使用 ajax 时收到错误请求

在 JQuery DataTable 中通过按钮单击传递 ID

即使我使用 [FromBody] C# 从视图(Ajax)发送请求时在控制器中收到 NULL 对象

jQuery:在mousemove事件期间检测按下的鼠标按钮

如何使用 JQuery Select 没有特定子元素的元素

使用 jQuery,当用户仍在编辑该字段时,如何将文本字段的第一个字母大写?

使用 jQuery 按文本内容 Select 选项

jquery click 不适用于 ajax 生成的内容

聚焦 时防止 iphone 默认键盘

为什么 Chrome 会忽略本地 jQuery cookie?

如何阻止 Chrome 进入调试模式?

如何清除/重置 jQuery UI Datepicker 日历上的选定日期?

Isotope 和 Masonry jQuery 插件之间的区别

Backbone.js - 事件,知道点击了什么

jQuery:如何找到父母的特定子元素?

如何使用 javascript 展开和折叠

javascript,是否有像 isArray 这样的 isObject 函数?

如何在jQuery中 Select 最后一个子元素?

Chrome 中的 AJAX 发送选项而不是 GET/POST/PUT/DELETE?

Twitter Bootstrap 中的树