1

I am trying to write and learn using Object.prototype and I am getting the error saying that this.issue is not a function when I call it within another method. What am I doing wrong that is causing it to through this Uncaught TypeError?

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

   })();

});

UPDATE: https://jsfiddle.net/czLtc82y/

user3897842
  • 105
  • 1
  • 10

1 Answers1

1

At handlers attached to change event for #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 references #sign , .number elements , not new Example object created by

var problem = new Example();

Try using Function.prototype.bind() to set this to new Example() : problem within .change() handlers

(function() {

    var problem = new Example();

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

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

})();

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


Alternatively, using $.proxy()

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

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

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

})();

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

guest271314
  • 1
  • 15
  • 104
  • 177