js代码在创建对象的新实例后显示错误

js code shows error after creating new instance of object

本文关键字:实例 显示 错误 代码 创建对象 新实例 js      更新时间:2023-09-26

当我创建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' 

有几个问题。

  1. 您在prototype中有一个打字错误。

  2. this.ev.on('click', this.userInput());应该是this.ev.on('click', this.userInput);——您希望传递对函数的引用,以便在用户单击时执行它,而不希望在绑定事件处理程序时调用它。

您拼写prototype错误;您的代码在其他方面执行得很好,尽管您打算用this.userInput引用该方法,而不是立即用this.userInput()调用它,因此,当页面加载时,您会同时得到消息'show''user'

有了这些修复程序,您的代码将按我所期望的那样运行:'user'只有在您单击链接时才会出现。

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

固定类型,只需稍作更改即可。

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();