Functions, Scope & Object Model

`this` Binding

this in a normal JavaScript function is determined by how the function is called, not where it is written. Arrow functions do not bind their own this; they capture it lexically.
  • Call form determines this
  • Method extraction loses the receiver
  • Arrow functions capture lexical this
  • bind creates a permanently-bound function
  • Class methods are not auto-bound
`this` binding rules
Call formthis value
obj.method()obj
fn()undefined in strict mode
fn.call(value)value
fn.apply(value, args)value
fn.bind(value)permanently value
arrow functionlexical surrounding this
Detached method bug
const user = {
  name: "Ana",
  greet() {
    return `Hi ${this.name}`
  },
}

const greet = user.greet
// greet() fails or returns wrong result because `this` is lost.

const safeGreet = user.greet.bind(user)
safeGreet() // "Hi Ana"
The receiver is part of the call expression, not stored inside the function automatically.
Sources
  • MDN JavaScript Guide and Referencethis; arrow functions
  • The Modern JavaScript TutorialObject methods and this
  • You Don’t Know JS YetObjects and Classes