javascript - 关于事件绑定时指定this的问题,求助
阿神
阿神 2017-06-22 11:53:57
[HTML讨论组]
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(){
        //    ...
    }
};
阿神
阿神

闭关修行中......

全部回复(1)
学习ing

讲真,第一种,很常见了,用多了也没啥。

当然,如果喜欢第二种,可以考虑用bind的polyfill(即在没有bind的情况下利用call等方法来实现bind)。

ps: es6的话,箭头函数就没有这种烦恼,但正如第二种的情况,只支持高版本现代浏览器。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号