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

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

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

Okay