3

我正在使用以下代码,但它返回以下错误

 Uncaught TypeError: Object [object HTMLAnchorElement] has no method 'userInput'

这是代码jsfiddle

var ClickEvent = function (event) {
    this.ev = $('.' + event);
    this.ev.on('click', function () { this.userInput(); });
};

ClickEvent.prototype = function () {
    return {
        userInput: function () {
            console.log('user');
        },

        show: function () {
            console.log('show');
        }
    };   
}();

var c = new ClickEvent('event');

userInputon()回调函数中调用函数,但它返回上面error

我怎么解决这个问题?

4

3 回答 3

5

问题是单击回调处理程序中的执行上下文(this)没有指向ClickEvent实例,它引用了被单击的 dom 元素。

你需要使用

this.ev.on('click', $.proxy(function () { this.userInput(); }, this));

演示:小提琴

或者

var that = this;
this.ev.on('click', function () { that.userInput(); });

演示:小提琴

于 2013-07-15T12:42:03.753 回答
2

this.userInput()嵌套在回调函数中,因此在其范围内。您可以将所需的实例外部化this,如下所示:

var ClickEvent = function (event) {
    var $this = this;
    $this.ev = $('.' + event);
    $this.ev.on('click', function () { $this.userInput(); });
};
于 2013-07-15T12:42:23.017 回答
0

"this"您的函数内部引用onclick"this.ev"

"$('.' + event);" 

不是你的对象"userInput""show"

于 2013-07-15T12:45:35.727 回答