Skip to content

Instantly share code, notes, and snippets.

@alexreardon
Created August 7, 2022 00:29
Show Gist options
  • Save alexreardon/b30e2690d8d36639f39470cc67528737 to your computer and use it in GitHub Desktop.
Save alexreardon/b30e2690d8d36639f39470cc67528737 to your computer and use it in GitHub Desktop.
How `this` works in javascript

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)

  1. new (new Person())
  2. explicit (call, apply, bind)
  3. implicit (obj1.foo())
  4. default (window, or undefined in strict mode)

Exceptions

  1. arrow functions (const hello = () => 'hi'). this is bound to the this context that the function is defined in
  2. ignored this (pass null as this to explicit binding - it will use the default binding)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment