0

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

1 Answer 1

1

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)

Sign up to request clarification or add additional context in comments.

1 Comment

as an explanation: I thought I was having a misunderstanding in js oop, but in fact, this relates to func hoisting, if I did declare the functions, as "function getUnit (...){....}" it would have worked I guess because of the hoisting func, but I won't be able to access the function as an object property.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.