Syncing account progress…

Back

Advanced · 12 min

Method calls and this

Understand the call receiver and preserve it when passing a method.

Use the call receiver

For an ordinary method called as object.method(), this refers to that object. The function declaration alone does not permanently bind a receiver.

const user = { name: "Ada", greet() { return `Hello, ${this.name}`; } };
console.log(user.greet());

Output

Hello, Ada

Bind a callback

bind() returns a function with a fixed this value. Use it when a method needs its object after being passed as a callback.

const counter = { value: 4, read() { return this.value; } };
const read = counter.read.bind(counter);
console.log(read());

Output

4

Put it into practice

  1. Predict each result before running the example.
  2. Complete the coding task, then explain why your solution works.

Try it yourself

Code runs on this device. When you are signed in, drafts sync to your account.

Keep the receiver

Bind read to counter before calling it, then display its result.

Practice