DEV Community

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

Posted on

3

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay