简体   繁体   中英

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM