对象在javascript中没有方法错误

Om3*_*3ga 3 javascript jquery javascript-events

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

 Uncaught TypeError: Object [object HTMLAnchorElement] has no method 'userInput'
Run Code Online (Sandbox Code Playgroud)

这是代码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');
Run Code Online (Sandbox Code Playgroud)

userInputon()回调函数内部调用函数,但它返回上面error.

我怎么解决这个问题?

Aru*_*hny 5

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

你需要使用

this.ev.on('click', $.proxy(function () { this.userInput(); }, this));
Run Code Online (Sandbox Code Playgroud)

演示:小提琴

要么

var that = this;
this.ev.on('click', function () { that.userInput(); });
Run Code Online (Sandbox Code Playgroud)

演示:小提琴