jquery – 在类方法中打字“this”

前端之家收集整理的这篇文章主要介绍了jquery – 在类方法中打字“this”前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我知道这可能是痛苦的基本,但我有一个艰难的时间包围我的头。
  1. class Main
  2. {
  3. constructor()
  4. {
  5. requestAnimationFrame(this.update); //fine
  6. }
  7.  
  8. update(): void
  9. {
  10. requestAnimationFrame(this.update); //error,because this is window
  11. }
  12.  
  13. }

看起来是这样的情况,我需要一个代理,所以让我们说使用Jquery

  1. class Main
  2. {
  3. constructor()
  4. {
  5. this.updateProxy = $.proxy(this.update,this);
  6. requestAnimationFrame(this.updateProxy); //fine
  7. }
  8.  
  9. updateProxy: () => void
  10. update(): void
  11. {
  12. requestAnimationFrame(this.updateProxy); //fine
  13. }
  14.  
  15. }

但是从Actionscript 3背景来看,我不太确定这里发生了什么。对不起,我不知道JavaScript开始和TypeScript结束。

  1. updateProxy: () => void

而且,我不相信我是这样做的。最后我想要的是我的类有一个a()函数,需要使用aProxy()访问,因为我觉得我写同样的事情两次?是正常吗?

解决方法

如果你想要“this”捕获的打字的方式,这样做是通过箭头功能。引用安德斯

The this in arrow functions is lexically scoped

我喜欢使用这个我的优势的方式是:

  1. class test{
  2. // Use arrow functions
  3. func1=(arg:string)=>{
  4. return arg+" yeah" + this.prop;
  5. }
  6. func2=(arg:number)=>{
  7. return arg+10 + this.prop;
  8. }
  9.  
  10. // some property on this
  11. prop = 10;
  12.  
  13. }

你可以看到在生成的javascript“this”被捕获之外的函数调用

  1. var _this = this;
  2. this.prop = 10;
  3. this.func1 = function (arg) {
  4. return arg + " yeah" + _this.prop;
  5. };

所以在函数调用(可能是窗口)内的“this”值不会被使用。

Try It

了解更多:https://www.youtube.com/watch?v=tvocUcbCupA&hd=1

猜你在找的jQuery相关文章