SamThYO
SamThYO

Reputation: 1

javascript: assign object function return value to object property

When I try to assign getUnit's return value to the inputUnit property, my script throws the error "this.getUnit is not a function". Can anyone help?

function ConvertHandler(initialString) {

  this.inputUnit = this.getUnit(initialString); // Error here
  this.inputNum = this.getNum(initialString);
  this.returnedUnit = this.getReturnUnit(this.inputUnit);
  this.returnedNum = this.convert();

  this.getNum = function(input) {
    return input.match(/((\d*\.?\d+)*(\/?)(\d*\.?\d+))/igm);
  };

  this.getUnit = function(input) {
    return input.match(/[A-Za-z]+$/i);
  };
}

var a = new ConvertHandler('4mi');
console.log(a.spellOutUnit());

Upvotes: 0

Views: 1409

Answers (1)

Cat
Cat

Reputation: 4226

It looks like you're trying to invoke the method before you've defined it.

The assignment succeeds if the order is reversed, as in this snippet:

function ConvertHandler(initialString) {
  this.getNum = function(input) {
    return input.match(/((\d*\.?\d+)*(\/?)(\d*\.?\d+))/igm);
  };
  this.getUnit = function(input) {
    return input.match(/[A-Za-z]+$/i);
  };
  this.inputUnit = this.getUnit(initialString);
  this.inputNum = this.getNum(initialString);
}

var a = new ConvertHandler('4mi');
console.log(a.inputNum);
console.log(a.inputUnit)

Upvotes: 1

Related Questions