如何在事件hanlder(JavaScript)中访问类实例? [英] How to access class instance in event hanlder (JavaScript)?

查看:74
本文介绍了如何在事件hanlder(JavaScript)中访问类实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码:

function Customer(name){
   this._name=name;
};

Customer.prototype.init=function(){
   $('#SetCreditLevel').click(function(){
      //best way to access this._name ?
      //this now points to DOM element

   });
}


推荐答案

这样的东西?
您可以通过设置自己的上下文来覆盖 this 的值,但是能够以的形式访问DOM对象非常有用。 jQuery中的这个,以及jQuery如何工作的基本部分。如果你要改变它,我会说你根本不习惯使用jQuery。所以相反,我在这里传递上下文作为参数......

Something like this? You could override the value of this by setting your own context, but it is very useful to be able to access the DOM object as this in jQuery, and a fundamental part of how jQuery works. If you were to change that, I'd say you're not hardly using jQuery at all. So instead, i'm passing context as a parameter here...

function Customer(name){
   this._name=name;
};

Customer.prototype.init=function(){
   $('#SetCreditLevel').click((function(context){
       return function() {
           alert(context._name);
           alert(this);
       }
   })(this));
}

这篇关于如何在事件hanlder(JavaScript)中访问类实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆