javascript - Regarding the problem of specifying this when binding events, please help
阿神
阿神 2017-06-22 11:53:57
0
1
785
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(){
        //    ...
    }
};
阿神
阿神

闭关修行中......

reply all(1)
学习ing

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!