DEV Community

Cover image for Understanding how `this` works in Javascript - Default Binding
Kevin J. Estevez
Kevin J. Estevez

Posted on

Understanding how `this` works in Javascript - Default Binding

We've seen in the previous post that this is bound depending on where is called, if you haven't read it please go back to

I'll start by saying that default binding is the last case which is going to match in case any other fit.

When default binding is applied, the global object will be bind to the called function, consider the next code:

function foo() {
    console.log(this.a);
}

function bar() {
    function bazz() {
        console.log(this.b);
    }
    bazz();
}

var a = 3;
var b = 5;

foo();  // 2
bar();  // 5
Enter fullscreen mode Exit fullscreen mode

It is worth to point out that global object will be eligible just if strict mode is not set either inside or outside the definition scope of the called function, but if 'use strict' is set at one of them, then this = undefined.

'use strict' inside function's definition

function foo() {
        'use strict';
    console.log(this.a);
}

var a = 3;

foo();  // TypeError: Cannot read property 'a' of undefined (this = undefined)
Enter fullscreen mode Exit fullscreen mode

'use strict' outside function's definition

function bar() {
    'use strict';
    function bazz() {
        console.log(this.b);
    }
    bazz();
}

var b = 5;

bar();  // TypeError: Cannot read property 'b' of undefined (this = undefined)
Enter fullscreen mode Exit fullscreen mode

It's worth to point out, despite of biding is entirely based on call-site, the 'use strict' concern is totally base on where the function itself is declared.

function foo() {
    console.log(this.a);
}

var a = 3;

(function(){
    'use strict';    
    foo();  // 3
})();
Enter fullscreen mode Exit fullscreen mode

Top comments (0)