So I have been researching the keyword "this" in JS and im not sure if I fully understand it clearly. So in an attempt to understand the "this" keyword, I started off by creating a JS object and seeing if I can return a value based on some math executed with the this keyword. The following code below is my initial attempt:
let myObject = { objectFunc: function() { this.thing = 10; }, addFunc: function(x) { let result = this.thing + x; return result; } } console.log(myObject.addFunc(20)); So I expected this console log to return 30, however Im getting a "NaN" in the console. Can someone explain to me why? and also point me to some easier to understand documentation/explanation that isn't the MDN linked above?
this.thingisundefinedwhenthis.thing + xis executed andundefined + 20isNaN. Why is itundefined? Because you never callmyObject.objectFun()to set the value ofthis.thing.this.