来自jquery回调的Javsacript对象引用

时间:2016-06-11 11:28:00

标签: javascript jquery

说我有这个代码

var SomeClass= function(id){
      this.id = guidGenerator();
      this.htmlElement = jQuery("#"+id);
      this.initClickHandler();
 };

 SomeClass.prototype = {
       initClickHandler: function(){
          this.htmlElement.on("click",function(e){
               //NEED A REFERENCE TO THE OBJECT HERE
               //IN A WAY THAT WILL ALLOW SOMETHING LIKE THIS
               //this.clickHandler();
          });
      },
      clickHandler: function(){
          alert(this.id);
      }
 };

SomeClassInstance1 = new SomeClass("a");
SomeClassInstance2 = new SomeClass("b");

我如何获得" SomeClass"的相关实例?在" ON"回调?

1 个答案:

答案 0 :(得分:0)

  

需要在这里引用对象,以允许类似这样的内容

使用变量来保留对this的引用:

SomeClass.prototype = {
  initClickHandler: function() {
    var me = this;
    this.htmlElement.on("click", function(e) {
      me.clickHandler();
    });
  },
  clickHandler: function() {
    alert(this.id);
  }
};

在您的情况下,您还可以绑定上下文wbith:fun.bind(thisArg[, arg1[, arg2[, ...]]])

this.htmlElement.on("click", this.clickHandler.bind(this));

另请注意,建议使用小写字母启动实例:

var someClassInstance1 = new SomeClass("a");
var someClassInstance2 = new SomeClass("b");