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 bindcreates a permanently-bound function- Class methods are not auto-bound
| Call form | this value |
|---|---|
| obj.method() | obj |
| fn() | undefined in strict mode |
| fn.call(value) | value |
| fn.apply(value, args) | value |
| fn.bind(value) | permanently value |
| arrow function | lexical surrounding this |
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"