未捕获的ReferenceError.在jQuery事件处理程序中找不到原型函数

sou*_*zin 1 html javascript jquery

按下提交按钮时出现以下错误:

Uncaught ReferenceError: addText is not defined 
Run Code Online (Sandbox Code Playgroud)
  • 为什么'click'处理函数找不到类原型函数'addText'?

  • 我该怎么做才能解决这个问题?

  • 如果这是处理事件的坏方法?(我来自java背景,我对使用面向对象的javascript的最佳实践不太了解)

这是代码:

<head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script src="js/jquery-1.9.1.js"></script>
    <script>
        //Class ctor
        function MyClass() {
            this.msg = "Hello World!";
        }
        //This method appends text to the given doc element
        MyClass.prototype.addText = function(doc) {
            $(doc).append('<br/>'+this.msg);
        };
       /*
        * This method adds a 'click' listener to the given element which 
        * calls the 'addText' method on its parent.
        */
        MyClass.prototype.listenToButton = function(btn) {
            $(btn).bind({
                click: function(event) {
                    addText($(this).parent());
                }
            });
        };

        $(document).ready(function() {
            //Create instance of class
            var c = new MyClass();
            //Listen to button
            c.listenToButton($("#mybutton"));
        });
    </script>
</head>
<body>
    <div>Button: <input id="mybutton" type="button" value="Submit"></div>
</body>
Run Code Online (Sandbox Code Playgroud)

显然我正在使用jQuery.提前致谢!

编辑

这是我学到的东西:

  • 'click'处理函数找不到函数'addText',因为'this'不再引用类实例而是引用事件的发送者.

  • 要解决这个问题,我应该将当前的'this'范围保存在处理函数之外的变量中.

  • 我不确定以这种方式处理事件是否是不好的做法,但它确实有效,所以我会继续使用它.

  • 此外,我应该使用'on'而不是'bind',因为它似乎'绑定'调用'on'无论如何.

谢谢大家的快速回复!

小智 5

试试这个:

MyClass.prototype.listenToButton = function(btn) {
        var that = this;
        $(btn).bind({
            click: function(event) {
                that.addText($(this).parent());
            }
        });
    };
Run Code Online (Sandbox Code Playgroud)

  • @SoulDZIN这是问题的典型解决方案,另一种选择是使用iife将`this`传递给函数,或者用`Function.bind`或`jQuery.proxy`来控制上下文.定义`that`var是处理它的常规方法. (2认同)