search

Home  >  Q&A  >  body text

javascript - Regarding the problem of specifying this when binding events, please help

function Tab($selector){
    var _this = this;
    
    //    这种可以保证this正确,但是这样写很累赘
    $selector.on("click", function(){
        _this.switchIndex();
    }); 
       
    //    不兼容ie某些浏览器
    $selector.on("click", this.switchIndex.bind(this));
    
    //    这种方式绑定会导致switchIndex内部的this为$selector,除了上面那些,
    //    还有其他比较自然的方式吗?
    $selector.on("click", this.switchIndex);
}
Tab.prototype = {
    switchIndex: function(){
        //    ...
    }
};
阿神阿神2761 days ago843

reply all(1)I'll reply

  • 学习ing

    学习ing2017-06-22 11:55:57

    To be honest, the first type is very common, and it doesn’t matter if you use it too much.

    Of course, if you like the second option, you can consider using bind’s polyfill (that is, using call and other methods to implement bind when there is no bind).

    ps: In es6, the arrow function does not have this trouble, but just like the second case, it only supports higher versions of modern browsers.

    reply
    0
  • Cancelreply