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(); } }
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
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: