Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 7.2 — call, apply and bind
JavaScript · Example 2 of 3

bind fixes lost this in a listener

Keep the bound function in a variable: removeEventListener needs the same function. Calling bind again would make a different one, and nothing would be removed.

Every function has three methods that let you choose this yourself: call runs the function now with arguments listed one by one, apply runs it now with arguments in an array, and bind doesn't run it at all but returns a new function whose this (and optionally first arguments) are fixed for good.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Use call to run function describe(unit) { return this.amount + " " + unit; } for { amount: 3 } with the unit "kg", and apply to do the same with { amount: 5 } and ["litres"].

02

Make const addTax = applyRate.bind(null, 0.18); from function applyRate(rate, price) { return price + price * rate; } and print addTax(100) and addTax(250).

03

Write logAll() that prints Math.min of its own arguments by borrowing: use Math.min.apply with the arguments object, and then the modern rest-parameter version.

Explain it without notes

01

What is the difference between call, apply and bind?

02

Why can't a bound function's this be changed, and is there any exception?

03

Write a simple version of Function.prototype.bind and explain it.

04

What is method borrowing? Give two real examples.

bind fixes lost this in a listener

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

count: 2
after removing, count: 2