DEV Community

Sheldon Nunes
Sheldon Nunes

Posted on • Updated on

Mini Quiz: Javascript Scoping

A quick quiz question on javascript scoping. Try and figure this out before executing in browser

If you were to create this object:

var person = {
    name: 'Dave',
    weight: 100,
    height: 180,
    calculateBMI: function() {
        console.log(this);
        function innerFunction() {
            console.log(this);
        }
        innerFunction();
    }
}

When running person.calculateBMI() what object will this be mapped to when logged by the innerFunction?

Top comments (6)

Collapse
 
lexlohr profile image
Alex Lohr • Edited

Depends on whether you 1) fix the code (you're missing a comma after the height and a closing } at the end) and 2) don't have "use strict" before the code (in which case this is set to undefined until explicitly set by call/apply or in prototypal methods); then the first console.log will show the person and the second one window/global (depending on your JS runtime).

Collapse
 
sheldonnunes profile image
Sheldon Nunes • Edited

Well spotted on the code error. Was not intentional and have since updated it :P

Collapse
 
avalander profile image
Avalander

Trick question, it won't run because it will throw a SyntaxError when parsing the code, so this won't be mapped to anything :P

Collapse
 
bakertx profile image
Aaron Baker

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?

Collapse
 
equiman profile image
Camilo Martinez

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();
    }
}
Collapse
 
theoutlander profile image
Nick Karnik

It is going to return window all the time