代码之家  ›  专栏  ›  技术社区  ›  Valentin V

如何在event hanlder(JavaScript)中访问类实例?

  •  1
  • Valentin V  · 技术社区  · 16 年前

    代码:

    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 回复  |  直到 16 年前
        1
  •  2
  •   David Hedlund    16 年前

    像这样的? 您可以重写 this

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