re: Mini Quiz: Javascript Scoping VIEW POST

VIEW FULL DISCUSSION
 

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?

 

Because innerFunction have another different scope. Then this inside reference to function and not to person.

You can solve it adding 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();
    }
}
code of conduct - report abuse