-2

I got the result at the console when calling the function with 'calculator', but it is showing undefined when using the 'this' keyword

const calculator = {
  calcBMI: function (mass, height) {
    const BMI = mass / height ** 2;
    return BMI;
  },
  firstName: "Arvind",
};

console.log(calculator.calcBMI(6, 1.8));
console.log(this.calcBMI(6, 1.8));
  • `this` will not be equal to `calculator`. The actual value will be context dependant and execution dependant but likely `window` or `undefined` at least in the code you show. – VLAZ Jan 19 '21 at 12:30
  • 3
    I have absolutely no idea why you would expect `this` to resolve to the object assigned to `calculator` given that code. – Quentin Jan 19 '21 at 12:31

1 Answers1

0

Here this represents the window object. There is no calcBMI method defined in window object. So it is returning undefined

const calculator = {
  calcBMI: function(mass, height) {
    const BMI = mass / height ** 2;
    return BMI;
  },
  firstName: "Arvind",
};

console.log(this)
brk
  • 43,022
  • 4
  • 37
  • 61