this, call, apply, bind

Rules for this

How the function is calledthis is
obj.method()obj
plain fn()undefined in strict mode / the global object in sloppy mode
new Fn()the new object
fn.call(x), fn.apply(x), fn.bind(x)x
arrow functionthe this of the surrounding scope

call, apply and bind

Example

function introduce(greeting, punctuation) {
  return greeting + ", I am " + this.name + punctuation;
}
const asha = { name: "Asha" };
console.log(introduce.call(asha, "Hello", "!"));     // args one by one
console.log(introduce.apply(asha, ["Hi", "."]));     // args as an array
const bound = introduce.bind(asha, "Namaste");      // new function, this fixed
console.log(bound("!!"));

Output

Hello, I am Asha!
Hi, I am Asha.
Namaste, I am Asha!!

Fixing Lost this

Example

class Clicker {
  count = 0;
  constructor() { this.handleBound = this.handle.bind(this); }
  handle() { this.count++; return this.count; }
  arrow = () => ++this.count;         // arrow field keeps this too
}
const c = new Clicker();
const { handleBound, arrow } = c;     // detached, like an event callback
handleBound();
arrow();
console.log(c.count);

Output

2