I find it easiest to make sense of this
as follows:
- It’s an implicit parameter of functions (other than arrow functions).
- It’s always provided when we invoke such functions – how depends on how we invoke them.
Demo:
import assert from 'node:assert/strict';
//========== `this` is an implicit parameter of getThis() ==========
function getThis() {
return this;
}
const obj = { method: getThis };
// Invocation via function call: `this` is implicitly `undefined`.
assert.equal(
getThis(), undefined
);
// Invocation via `.call()`: `this` is the first argument.
assert.equal(
getThis.call('abc'), 'abc'
);
// Invocation via method call: `this` is the receiver of the call.
assert.equal(
obj.method(), obj
);
//========== `this` is shadowed like explicit parameters ==========
outerFunction.call('outer', 'outer');
function outerFunction(outerParameter) {
assert.equal(this, 'outer');
assert.equal(outerParameter, 'outer');
innerFunction.call('inner', 'inner');
function innerFunction(innerParameter) {
assert.equal(this, 'inner');
assert.equal(innerParameter, 'inner');
assert.equal(outerParameter, 'outer');
}
}
More information on this
topic: https://exploringjs.com/impatient-js/ch_objects.html#methods-and-this