Lessons in this course (16)

6. The `this` keyword, call, apply and bind

Intermediate★ Must knowLesson 6 of 16

this is decided by how a function is called (except arrow functions, which take this from their enclosing scope).

Call stylethis
obj.method()obj
Plain call fn()undefined in strict mode / modules; global object in sloppy mode
new Fn()The new object
fn.call(ctx, a, b) / fn.apply(ctx, [a, b])ctx
fn.bind(ctx)Returns a new function permanently bound to ctx
Arrow functionLexical this (from where it's defined)
DOM event handler (function)The element (event.currentTarget)
js
const user = {
  name: "Divakar",
  greet() { return `Hi ${this.name}`; },
  greetLater() { setTimeout(() => console.log(this.name), 100); },   // arrow keeps 'this'
};
const greet = user.greet;
greet();                        // "Hi undefined" (lost 'this') in non-strict; TypeError in strict
greet.call({ name: "Asha" });   // "Hi Asha"
const bound = user.greet.bind(user);
bound();                        // "Hi Divakar"