为了账号安全,请及时绑定邮箱和手机立即绑定

JS面向对象时,组件的click事件怎么调用自身的方法?

JS面向对象时,组件的click事件怎么调用自身的方法?

慕妹3146593 2018-09-04 14:13:19
在《你不知道的JS》中,有一个委托控件对象的例子,使用了jquery,我想用原生js改写其中遇到这句this.$el.click(this.onClick.bind(this));改写一直失败。麻烦各位可以给我解惑。我的方案结果点击按钮控制台无反应        Button.build=function($where){          this.insert($where);          this.$el.onclick=function(){             Button.onClick.bind(this);           }         };点击控制台显示Button "undefined" clicked!        Button.build=function($where){          this.insert($where);          this.$el.onclick=function(){             Button.onClick.call(this);           }         };点击后显示Uncaught TypeError: Cannot read property 'call' of undefinedButton.build=function($where){               this.insert($where);          this.$el.onclick=function(){            this.onClick.call(this);           }                    };分析this.$el.onclick之后,console.log(this),显示的是一个dom元素<button>xxx</button>疑问组件绑定click事件如何调用自身的方法?jquery是如何实现这个绑定的?谢谢大家!源代码:
查看完整描述

1 回答

?
蓝山帝景

TA贡献1843条经验 获得超7个赞

btn.onclick = Button.onClick.bind(this)


查看完整回答
反对 回复 2018-10-07
  • 1 回答
  • 0 关注
  • 1619 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信