Skip to content

Instantly share code, notes, and snippets.

@rauschma
Last active December 18, 2022 16:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rauschma/afc3bee7be2e13b1c9f87f3edf85fdfb to your computer and use it in GitHub Desktop.
Save rauschma/afc3bee7be2e13b1c9f87f3edf85fdfb to your computer and use it in GitHub Desktop.

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment