如何在事件处理程序(JavaScript)中访问类实例?

时间:2009-12-14 10:30:30

标签: javascript jquery

代码:

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

   });
}

2 个答案:

答案 0 :(得分:2)

答案 1 :(得分:2)

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

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

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