We're a place where coders share, stay up-to-date and grow their careers.
Because innerFunction have another different scope. Then this inside reference to function and not to person.
this
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(); } }
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: