【问题标题】:Uncaught TypeError * is not a function [duplicate]未捕获的 TypeError * 不是函数 [重复]
【发布时间】:2016-01-09 05:40:10
【问题描述】:

我正在尝试使用 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/

【问题讨论】:

  • 你能在 JSFiddle 中重现它吗?这样会更容易找到问题
  • 因为里面全是“伪代码”,而且你提交的真实代码部分是有效的,没有机会得到答案
  • @Pikamander2 我现在就创建一个
  • 你在哪里打电话给issue()?如果你在你的 IIFE 中调用 solution.issue() 或 solution.updateNumber() 或 solution.updateSign(),就可以了。
  • @JasmineOT 我在 .updateNumber 和 .updateSign 中调用 this.issue()。我还附上了一个 JSFiddle

标签: javascript jquery oop


【解决方案1】:

在附加到 change 事件的处理程序上,#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 创建的对象

var problem = new Example();

尝试使用Function.prototype.bind() 将this 设置为new 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/

【讨论】:

  • 您可能想详细说明为什么需要这样做。
  • @FelixKling 查看更新后的帖子
  • 感谢@guest271314 的回答和解释!
猜你喜欢
  • 1970-01-01
  • 2017-01-26
  • 2018-01-02
  • 1970-01-01
  • 2016-01-21
  • 2020-09-05
  • 2020-01-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多