-1

当我创建 ClickEvent 对象的新实例时,它返回以下错误。单击此处获取 jsfiddle 代码。下面是我的代码

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

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

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

var c = new ClickEvent('event');
    c.show();

为什么会显示此错误,我该如何解决?

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

4 回答 4

3

有几个问题。

  1. 你有一个错字prototype

  2. this.ev.on('click', this.userInput()); should be this.ev.on('click', this.userInput); - you want to pass a reference to the function so it's executed when the user clicks, you don't want to call it when binding the event handler.

于 2013-07-15T10:43:55.180 回答
2

You spelt prototype wrong; your code otherwise executes fine, though you meant to reference the method with this.userInput rather than invoking it right away with this.userInput(), and due to this you get both messages 'show' and 'user' when the page loads.

With those fixes in place, your code functions as I expect you intend: the 'user' only appears when you click on the link.

于 2013-07-15T10:44:06.383 回答
0

该错误意味着在 javascript 库中找不到方法 userInput 。我可以说这很可能是因为您没有在第 3 行之前的任何地方引用 userInput 变量。而且 .on() 有两个参数:(“EVENT”,“FUNCTION”)。在您的代码中, this.userInput 不是一个函数,也不能作为一个函数。

于 2013-07-15T10:37:58.327 回答
-1

fixed Type, and a little change , this works.

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

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

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

var c = new ClickEvent('event');
c.show();
于 2013-07-15T10:45:32.447 回答