Default Binding - THIS Keyword — Part-2

Default binding is one of the 4 bindings that impacts the value of this keyword and the most commonly seen and understood

Meher Howji avatar image
··- views
A random image as the post cover
Photo by Marek Szturc on Unsplash

It’s the most common way to invoke a function. You already know it and have seen it a million times. It looks like this:

function name() {
console.log(this)
}
name()

Now, when you load such a code in your browser window through the dev console or an HTML document. The function name gets added to the global object, and in the case of a browser (the other being the Node environment), the global object is your window object.

The window object contains a number of functions, namespaces, objects, and constructors, and these are available globally across your codebase. And so when we ask JS about this within a function like this, what we get back is window object:

Window {
    alert: ƒ alert()
    atob: ƒ atob()
    blur: ƒ blur()
    btoa: ƒ btoa()
    caches: CacheStorage {}
    cancelAnimationFrame: ƒ cancelAnimationFrame()
    cancelIdleCallback: ƒ cancelIdleCallback()
    captureEvents: ƒ captureEvents()
    chrome: {loadTimes: ƒ, csi: ƒ}
    clearInterval: ƒ clearInterval()
    clearTimeout: ƒ clearTimeout()
    ...
}

But Why?

When an identifier, in our case, the function name, is added to the global object.

And when we are invoking the name` function, what JavaScript is actually doing behind the scenes is:

window.name()

And it should be clear why this keyword is pointing to the window object because our call-site clearly shows that name should be invoked from the perspective of the window. And that's why this in a function in global scope points to the window object.

Strict Mode

In strict mode, it's quite simple. You will get back undefined, which is an appropriate response and avoids all the confusion.

"use strict"
function name() {
console.log(this) //outputs undefined
}
name()

Even this, too...

function name() {
"use strict"
console.log(this) //outputs undefined
}
name()

So that's one way the value of this keyword can have a different value. Now, let's look at the next part which is Implicit Binding