This binding in JavaScript - 1. Default binding
Spyros Argalias
Posted on March 22, 2020
This post (This binding in JavaScript - 1. Default binding) was originally published on Sargalias.
In this series we talk about this
binding in JavaScript.
This is a very important topic. It's also something that even experienced developers frequently get wrong and / or have to think about.
Basically in JavaScript there are 4 modes for this
binding. Make that 5 if we include arrow functions.
In order of lowest priority to highest priority, here they are:
- Default binding
- Implicit binding
- Explicit binding
- New binding
- Arrow functions
In this post we'll talk about default binding.
How default binding works
Default binding is what happens if you don't use any other kind of binding.
If we call any function plain / without a "." before it, we will get default binding.
An example of a plain function call is foo()
. Notice that the function call does not have a "." before it.
An example of a function call that's not plain is obj.foo()
.
In the plain function call foo()
, default binding applies.
When default binding applies, this
is the window
object in normal mode and undefined
in strict mode.
Examples for default binding
Here are some examples for default binding to illustrate the point a bit more.
Plain function call
Consider the following code.
'use strict';
function foo() {
console.log(this);
}
foo();
What will the code above output?
Answer: undefined
Explanation:
We call our function with this code: foo()
.
The code foo()
is a plain function call. It does not have a ".
" before it. Therefore default binding applies. So the answer is window
in normal mode or undefined
in strict mode.
As we are in strict mode, the answer is undefined
.
Synchronous function reference call
Consider the following code.
'use strict';
const obj = {
foo() {
console.log(this);
},
};
const foo = obj.foo;
foo();
What will the code above output?
Answer: undefined
Explanation:
We call our function with this code: foo()
.
That code decides everything.
As it is a plain function call, we're using default binding, so this
is undefined
.
In combination with the line above it, it may be more difficult to see.
const foo = obj.foo;
foo();
We might understandably think that it should result in this
being obj
.
However that's not what happens. The only thing that matters is the function call, and the function call is plain and without a "." before it.
Therefore we are using default binding and this
becomes undefined.
Posted on March 22, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
July 6, 2024