Search code examples
javascriptoopmultiplication

Wrong return value when multiplying


The output of console.log() is the value of width when I use the getRatioValue() function to multiply the inserted value of height and the calculated ratio. I cannot find why this is happening.

var soFunction = function(args) {
   this.width = args.width || 0;
   this.height = args.height || 0;

   this.getRatioValue = function(value) {
      var ratio = this.width / this.height;
      return value * ratio;
   };

   console.log(this.getRatioValue(this.height)); // returns 1200
}

// Initialize object
var test = new soFunction({width: 1200, height: 980});

Solution

  • It is an simple mathematic operation. If you will write your function on one line you will get.

    value is equal to height, so

    return this.height * this.width / this.height
    

    this.height's destroy each other and it returns the this.width