javascript - JS面向对象时,组件的click事件怎么调用自身的方法?
怪我咯
怪我咯 2017-04-11 12:30:24
[JavaScript讨论组]

在《你不知道的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 undefined

Button.build=function($where){
          this.insert($where);
          this.$el.onclick=function(){
            this.onClick.call(this);
          }
        };

分析
this.$el.onclick之后,console.log(this),显示的是一个dom元素

疑问
组件绑定click事件如何调用自身的方法?jquery是如何实现这个绑定的?
谢谢大家!

源代码:

var Widget = {
          init: function(width, height) {
            this.width = width || 50;
            this.height = height || 50;
            this.$el = null;
          },
          insert: function($where) {
            if (this.$el) {
              this.$el.css({
                width: this.width + 'px',
                height: this.height + 'px'
              }).appendTo($where);
            }
          }
        };
        var Button = Object.create(Widget);
        Button.setup = function(width, height, label) {
          this.init(width, height);
          this.label = label || 'default';
          this.$el = $('
怪我咯
怪我咯

走同样的路,发现不同的人生

全部回复(2)
PHP中文网
btn.onclick = Button.onClick.bind(this)
ringa_lee

因为你看的是《你不知道的js》,所以大家都不知道。就酱。

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

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