在jquery事件中使用Javascript"this"

Mic*_*Fin 1 javascript jquery function this

如何在Jquery更改函数中正确调用functionOne?"this"不再引用该对象.

NameSpace.object = {
  functionOne: function(){
     // stuff
  },
  functionTwo: function(){
     this.functionOne();  // this works correctly
  },
  functionThree: function(){
    $('input').change(function(){
       if ( $(this).val() > 1) {
         this.functionOne(); // this is no longer calling function one 
       }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

jfr*_*d00 6

由于您要使用两个不同的值并且jQuery已经将其中一个放入其中this,因此您可以将另一个值保存在更高范围的变量中:

NameSpace.object = {
  functionOne: function(){
     // stuff
  },
  functionTwo: function(){
     this.functionOne();  // this works correctly
  },
  functionThree: function(){
    // save value if this so it can be used later in this scope
    var self = this;
    $('input').change(function(){
       if ( $(this).val() > 1) {
         self.functionOne();
       }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

或者,因为这是一个静态命名NameSpace.object,你也可以直接引用该名称:

NameSpace.object = {
  functionOne: function(){
     // stuff
  },
  functionTwo: function(){
     this.functionOne();  // this works correctly
  },
  functionThree: function(){
    $('input').change(function(){
       if ( $(this).val() > 1) {
         NameSpace.object.functionOne();
       }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

或者,由于jQuery提供了一种.change( [eventData], handler )将数据传递给事件处理程序的机制,因此您也可以使用它:

NameSpace.object = {
  functionOne: function(){
     // stuff
  },
  functionTwo: function(){
     this.functionOne();  // this works correctly
  },
  functionThree: function(){
    $('input').change(this, function(e){
       if ( $(this).val() > 1) {
         e.data.functionOne();
       }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

jQuery机制不是我最喜欢的,因为我认为调用的代码e.data.functionOne()不太明显(读者必须回顾代码才能弄清楚是什么e.data),但这只是我对这种情况的个人看法.