0

I came across this interesting and weird issue when playing around with a simple object.The type of both the numbers declared as properties of the object obj are numbers as output in the Chrome dev console. The this should have referred to the current object.However, when trying to calculate the sum , the result is NaN instead of the sum. Interestingly, using the object to directly reference the numbers works when calculating the sum.

var obj={
number1: 2, 
number2: 3,
sum : this.number1 + this.number2
};
obj.sum;

NaN

BUT the following code works

var obj={
number1: 2, 
number2: 3,
sum : obj.number1 + obj.number2
};
obj.sum;

5
Ananta K Roy
  • 924
  • 1
  • 7
  • 12
  • Just do the later, then. Don't use this. Simple! – VirxEC Sep 06 '19 at 12:57
  • 1
    "*The `this` should have referred to the current object.*" [No, it doesn't](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) it references *the current context* and that will depend on how the code you are running has been executed. If it's inside a function it *might* be the context of the function but that can be changed with stuff like `.call` or `.apply`. – VLAZ Sep 06 '19 at 12:58

0 Answers0