this
is the runtime context of afunction
.this
is determined by the call site- the same function can be executed with different
this
runtime contexts. You can think ofthis
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();
(In order of precedence)
- new (
new Person()
) - explicit (
call
,apply
,bind
) - implicit (
obj1.foo()
) - default (
window
, orundefined
in strict mode)
- arrow functions (
const hello = () => 'hi'
).this
is bound to thethis
context that the function is defined in - ignored
this
(passnull
asthis
to explicit binding - it will use the default binding)