We're a place where coders share, stay up-to-date and grow their careers.
The calculateBMI method this mapping to the person object makes sense to me, but the innerFunction mapping to the Window object was a surprise. Anybody care to explain?
this
person
Because innerFunction have another different scope. Then this inside reference to function and not to person.
You can solve it adding self:
self
var person = { name: 'Dave', weight: 100, height: 180, calculateBMI: function() { console.log(this); var self = this; function innerFunction() { console.log(self); } innerFunction(); } }
Or with arrow function:
var person = { name: 'Dave', weight: 100, height: 180, calculateBMI: function() { console.log(this); let innerFunction = () => { console.log(this); } innerFunction(); } }
The calculateBMI method
this
mapping to theperson
object makes sense to me, but the innerFunction mapping to the Window object was a surprise. Anybody care to explain?Because innerFunction have another different scope. Then
this
inside reference to function and not to person.You can solve it adding
self
:Or with arrow function: