this binding
this is the runtime context of a function.
this is determined by the call site
the same function can be executed with different this runtime contexts. You can think of this as another arguement to the function
Comparison: scopes are generally defined at compile time (exception: eval)
const person = {
name: 'Alex',
getName() {
return this.name;
}
}
const foo = person.getName;
// using default binding (`undefined` in strict mode)
foo();
// using explicit binding
person.getName.call({name: 'Ben'});
// using implicit binding
// using `person` as the 'this' binding
person.getName();
Rules
(In order of precedence)
new (new Person())
explicit (call, apply, bind)
implicit (obj1.foo())
default (window, or undefined in strict mode)
Exceptions
arrow functions (const hello = () => 'hi'). this is bound to the this context that the function is defined in
ignored this (pass null as this to explicit binding - it will use the default binding)