从 jquery 回调中获取类实例

发布于 2024-10-03 21:52:23 字数 443 浏览 1 评论 0原文

如何从 jquery 的回调中获取“MyClass”实例。

function MyClass(){      

  this.message = 'Hello World'; // I need access to this variable in the callback

  //registering class member function as callback
  $('div').draggable({drag:this.onDrag});

  this.onDrag = function(event,ui){

   alert(this.message); // 'this' is jquery object, not MyClass instance;

  }
}

PS 具有“MyClass”实例的全局变量或将实例存储到数据中是不可取的。

谢谢你!

How to get a 'MyClass' instance in the callback from jquery.

function MyClass(){      

  this.message = 'Hello World'; // I need access to this variable in the callback

  //registering class member function as callback
  $('div').draggable({drag:this.onDrag});

  this.onDrag = function(event,ui){

   alert(this.message); // 'this' is jquery object, not MyClass instance;

  }
}

P.S. Global variable with 'MyClass' instance or storing instance into data is not desirable.

Thank you!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

眼藏柔 2024-10-10 21:52:23

这里最好的选择(IMO)只是保留另一个引用,我更喜欢 self,如下所示:

function MyClass(){      
  var self = this;
  this.message = 'Hello World'; // I need access to this variable in the callback

  //registering class member function as callback
  $('div').draggable({drag:this.onDrag});

  this.onDrag = function(event,ui){    
    alert(self.message);
  }
}

另一种选择是混淆另一个你无法真正控制的插件的上下文(再次,IMO)它是并不是真正必要,在许多情况下,只需使用另一个引用来访问您的类就同样容易且不那么混乱。

The best option here (IMO) is just to keep another reference, I prefer self, like this:

function MyClass(){      
  var self = this;
  this.message = 'Hello World'; // I need access to this variable in the callback

  //registering class member function as callback
  $('div').draggable({drag:this.onDrag});

  this.onDrag = function(event,ui){    
    alert(self.message);
  }
}

The alternative is messing with context of another plugin you don't really control when (again, IMO) it's not really necessary, just having another reference to access your class is just as easy and less confusing in many cases.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文