Advanced 12 min
Objects, prototypes, and this
A prototype lets objects share behavior, and this often refers to the receiver in a method call.
How it works
Look at the expression used when the function is called. When you see book.label(), the receiver is book. When you only see read(), the call no longer names book. Binding the original method stores the intended receiver for those later calls.
Walk through an example
In book.label(), an ordinary method sees book as this. If you store book.label in a variable and call the variable by itself, that original receiver is lost.
What to watch for
Use a wrapper such as () => book.label() or bind the method when passing it where the receiver should remain book.
Code example
const book = { title: 'Loops', label() { return this.title; } };
const read = book.label.bind(book);
console.log(read());Check your understanding
Which object does this refer to inside label?
See the example and explanation
- Worked example
- Given
const read = book.label.bind(book); read() - Answer
book
Binding creates a function that calls the target with book as its receiver.