未捕获的TypeError *不是函数

时间:2016-01-09 05:40:10

标签: javascript jquery oop

我正在尝试使用Object.prototype编写和学习,我收到的错误是this.issue在我在另一个方法中调用它时不是函数。我做错了什么导致它通过这个Uncaught TypeError?

Javascript:

$(document).ready(function() {
   var Example = function() {
       this.number1 = null;
       this.number2 = null;
   };

   Example.prototype.issue = function() {
       //Logic is here...
    };

   Example.prototype.updateNumber = function() {
       //more logic is here...
       this.issue();
   };

   Example.prototype.updateSign = function() {
       //logic here...
       this.issue();
   };

   (function() {
       var solution = new Example();

   })();

});

更新:https://jsfiddle.net/czLtc82y/

1 个答案:

答案 0 :(得分:1)

附加于change的{​​{1}}事件的处理程序,#sign

.number

Example.prototype.newNumber = function(event) { if (event.currentTarget.id === 'number1') { this.number1 = parseFloat($(event.currentTarget).val()); } else { this.number2 = parseFloat($(event.currentTarget).val()); } this.issue(); }; Example.prototype.newSign = function(event) { this.sign = $(event.currentTarget).val(); this.issue(); }; 引用了this#sign个元素,而不是

创建的.number个对象
new Example

尝试使用Function.prototype.bind()var problem = new Example(); 设置为thisnew Example() problem处理程序中的.change()

(function() {

    var problem = new Example();

    $("#sign").change(problem.newSign.bind(problem));

    $(".number").change(problem.newNumber.bind(problem));

})();

jsfiddle https://jsfiddle.net/czLtc82y/1/

或者,使用$.proxy()

(function() {
    var problem = new Example();

    $("#sign").change($.proxy(problem.newSign, problem));

    $(".number").change($.proxy(problem.newNumber, problem));

})();

jsfiddle https://jsfiddle.net/czLtc82y/2/