从事件处理程序调用方法

3
我正在处理的代码中,每次调用init方法时都会收到以下错误提示:

this.addElement不是一个函数

。这是因为我不能从事件处理程序中调用方法吗?
function editor () {

    this.init = function () {
        $("#area").bind('click' , this.click_event );
        
    }

    this.addElement = function () {
        console.log("adding element");
    }

    this.click_event = function(event) {
        this.addElement();
        console.log("click event in x : "+event.data);
    }
}

你绝对可以从事件处理程序中调用方法。问题是,在click_event内部,this是什么?理解这一点,世界就是你的海螺了。 - Amadan
即使我删除了“this”,我仍然会收到相同的错误。 - Ayoub M.
如果您删除this,它仍然隐含存在:this.addElement()addElement() 是相同的。但是检查this - 很可能这不是您想要的。 - Amadan
2
在您的点击回调函数中,this 不再指向 editor 对象。在 addElement 函数内部执行 console.log(this) 以查看 this 指向的是什么。 - Anurag
2个回答

9
function editor () {
    var that = this;

    this.init = function () {
        $("#area").bind('click' , this.click_event );

    }

    this.addElement = function () {
        console.log("adding element");
    }

    this.click_event = function(event) {
        that.addElement();
        console.log("click event in x : "+event.data);
    }
}

你应该阅读这本书,JavaScript: the Good Parts并访问Crockenator的网站crockford.com

你还可以在这里阅读关于JavaScript "this"问题的内容http://www.quirksmode.org/js/this.html


@Ayoub:基本上,this在JavaScript中与其他一些语言(如Java或C#)中的this非常不同。它完全取决于函数的调用方式,而不是定义的位置。更多信息请参见:http://blog.niftysnippets.org/2008/04/you-must-remember-this.html - T.J. Crowder

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接