Sub topic 2
Why Methods Lose Their this
This chapter assumes you know how to write functions and objects, and that a method call like obj.fn() sets this to obj.
Why Methods Lose Their this
this comes from the call site, which is the place where the function is called. It does not come from the place where the function was defined. If you copy a method into a variable or pass it as a callback, the function no longer has an object in front of the dot. The call becomes a plain call, so this is undefined in strict code.
'use strict';
const counter = {
count: 0,
increment() {
this.count++;
return this.count;
}
};
console.log(counter.increment()); // 1
const inc = counter.increment;
try {
inc();
} catch (e) {
console.log(e instanceof TypeError); // true: this is undefined
}setTimeout(counter.increment, 100) breaks in the same way. Only the function is passed along, and the object stays behind.
Setting this with call and apply
call and apply run a function right away with the this you choose. They differ only in how you pass the arguments. call takes them one by one, and apply takes them as an array.
function greet(greeting, punctuation) {
return `${greeting}, ${this.name}${punctuation}`;
}
const ada = { name: 'Ada' };
console.log(greet.call(ada, 'Hello', '!')); // 'Hello, Ada!'
console.log(greet.apply(ada, ['Hi', '?'])); // 'Hi, Ada?'Locking this with bind
bind does not run the function. It returns a new function whose this is fixed for good, and it can also fix leading arguments. This makes bind the standard fix for extracted methods and callbacks.
function greet(greeting, punctuation) {
return `${greeting}, ${this.name}${punctuation}`;
}
const greetAda = greet.bind({ name: 'Ada' }, 'Hey');
console.log(greetAda('.')); // 'Hey, Ada.'
console.log(greetAda.call({ name: 'Bob' }, '!')); // 'Hey, Ada!' (call cannot override bind)Constructors and the new Keyword
new creates a fresh object, sets it as this, runs the function, and returns the object unless the function returns an object of its own. new takes precedence over bind.
function Box(value) {
this.value = value;
}
const b1 = new Box(1);
console.log(b1.value); // 1
const BoundBox = Box.bind({ value: 'ignored' });
const b2 = new BoundBox(42);
console.log(b2.value); // 42: new overrides the bound this| Call form | this |
|---|---|
| `new Fn()` | the new object |
| `fn.bind(o)()` | `o` |
| `fn.call(o)` / `fn.apply(o)` | `o` |
| `obj.fn()` | `obj` |
| `fn()` (strict) | `undefined` |
Exercise
Given const user = { name: 'Lin', hi() { return this.name; } };, why does setTimeout(user.hi, 0) fail to return 'Lin', and what one-line change fixes it?
Show answer
Passing user.hi hands over only the function, so the timer calls it as a plain function and this is not user. Write setTimeout(user.hi.bind(user), 0) instead, which locks this to user.
Exercise
What does new (function () { this.x = 1; }.bind({ x: 2 }))().x evaluate to?
Show answer
1. new creates a fresh object as this, so the bound object { x: 2 } is ignored.