JS 字面量面向对象访问报not a function

var page={
    init:function(){
        this.initEvents()
    },
    bindEvent: function (target, type, name) {
        $(target).bind(type, function (e) {
            e.preventDefault();
            name(e)
            })
    },
    initEvents: function () {
        this.bindEvent('.pic-egg1', 'click', this.showDiag)
        this.bindEvent('.pic-egg2', 'click', this.showDiag)
    },
    showDiag: function () {
        this.hideDiag()
    },
    hideDiag:function(){
        console.log('出不来')
    }
}

控制器报这个错误

hideDiag is not a function

阅读 2.9k
4 个回答

$('#foo').bind(event, eventHandler) 中的 eventHandler 指向 #foo 选择器代表的 dom 元素本身,所以就会出现 xx is not function 的错误了。

要解决的话,很简单啊,使用 bindapply 或者 call 绑定方法至 page 对象即可。

function 不是 functiong

你确定吗?原封未动的拷贝在sublim都能运行

你绑定事件,showDiag回调的时候,this已经不是page了。手机回答,具体解决方式不大记得了,搜一下js如何传递this之类的

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题