In JavaScript, the meaning of this depends on the execution context in which it is used. The binding of this can seem very confusing at first, but mastering context binding unlocks writing reusable code that nimbly passes around object context. Understanding this certainly takes JavaScript skills to the next level!
In this deep dive, we’ll break down how this behaves and some best practices around it.
The Chameleon this
First realize this
is not fixed — it depends on invocation:
// Standalone
console.log(this); // window
// Method call
user.sayHi(); // user
// Constructed
let user = new User(); // newly constructed object
this
adapts depending on where it is called from, aka execution context.
Function Invocation: New Binding
When a function is invoked with new, this gets set to the newly constructed object:
function User(name) {
// Bound as new object
this.name = name;
}
let user = new User('Jack');
console.log(user.name); // 'Jack'