JavaScriptFundamental (ES6), part 1
The this keyword explained in seven cases in JavaScript
142 this, in the seven places it changes meaning
hardTake one function and call it seven ways: as a method, detached, through call and apply and bind, as an arrow written in an object literal, and as a callback handed to map. Report what this was each time. Then show that binding twice does not rebind, that new ignores a bound this, and that a class field holding an arrow survives being detached where a method does not.
Stuck? Three hints, smallest first
- 1. For a plain function,
thisis decided at the CALL, by whatever sits to the left of the dot. There is nothing to the left of the dot indetached(). - 2. An arrow has no
thisof its own, so an arrow in an object literal captures the scope around the literal, not the object. - 3.
maptakes a second argument,thisArg. That, an arrow, orbindare the three ways to keep the method’sthisinside the callback.
const topLevelThis = typeof this; // a strict function scope, so: undefined
const stall = {
name: 'Balogun stall',
items: ['gari', 'rice'],
who() { return this.name; }, // 1. decided by the call site
whoArrow: () => (this === undefined ? '<no this>' : 'the stall'), // 2. captured, not the object
labelPlain() { // 3. a plain callback loses it
return this.items.map(function (item) {
return (this === undefined ? '<no this>' : this.name) + '/' + item;
});
},
labelArrow() { // 4. an arrow keeps it
return this.items.map((item) => this.name + '/' + item);
},
labelThisArg() { // 5. so does map's second argument
return this.items.map(function (item) { return this.name + '/' + item; }, this);
},
labelBound() { // 6. and so does bind
const fn = function (item) { return this.name + '/' + item; }.bind(this);
return this.items.map(fn);
},
};
const asMethod = stall.who();
const detached = stall.who; // 7. same function, no receiver
let detachedResult;
try { detachedResult = detached(); } catch (e) { detachedResult = e.constructor.name; }
const kiosk = { name: 'Yaba kiosk' };
const borrowed = [stall.who.call(kiosk), stall.who.apply(kiosk), stall.who.bind(kiosk)()];
const boundOnce = stall.who.bind(kiosk);
const boundTwice = boundOnce.bind(stall); // the second bind cannot win
const rebound = boundTwice();
function Stallholder(name) { this.name = name; }
const BoundHolder = Stallholder.bind({ name: 'ignored by new' });
const built = new BoundHolder('Adaora');
class Counter {
constructor() {
this.n = 0;
this.bumpField = () => { this.n += 1; return this.n; }; // an own arrow property
}
bumpMethod() { this.n += 1; return this.n; } // lives on the prototype
}
const counter = new Counter();
const looseField = counter.bumpField;
const looseMethod = counter.bumpMethod;
let fieldResult, methodResult;
try { fieldResult = looseField(); } catch (e) { fieldResult = e.constructor.name; }
try { methodResult = looseMethod(); } catch (e) { methodResult = e.constructor.name; }
console.log('top level :', topLevelThis, '| as a method:', asMethod, '| detached:', detachedResult);
console.log('borrowed :', borrowed, '| arrow in a literal:', stall.whoArrow());
console.log('callbacks :', stall.labelPlain(), stall.labelArrow());
console.log('bind twice:', rebound, '| new on a bound fn:', built.name);
console.log('detached :', fieldResult, methodResult, '| counter.n:', counter.n);
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('at the top of a strict panel there is no this at all', topLevelThis, 'undefined');
test('called as a method, this is whatever sits left of the dot', asMethod, 'Balogun stall');
test('the same function with no receiver gets undefined, so the property read throws', detachedResult, 'TypeError');
test('call, apply and bind all aim it somewhere else', borrowed, ['Yaba kiosk', 'Yaba kiosk', 'Yaba kiosk']);
test('an arrow in an object literal captured the scope, not the object', stall.whoArrow(), '<no this>');
test('a plain callback in map loses this; arrow, thisArg and bind all keep it', [stall.labelPlain()[0], stall.labelArrow()[0], stall.labelThisArg()[0], stall.labelBound()[0]], ['<no this>/gari', 'Balogun stall/gari', 'Balogun stall/gari', 'Balogun stall/gari']);
test('binding an already bound function changes nothing', rebound, 'Yaba kiosk');
test('but new ignores the bound this while keeping the prototype', [built.name, built instanceof Stallholder], ['Adaora', true]);
test('a class field arrow survives detachment; a prototype method does not', [fieldResult, methodResult, counter.n], [1, 'TypeError', 1]);
this is not a property of a function. It is an argument, supplied afresh at every call, and the only thing that decides it for an ordinary function is the call expression: obj.fn() passes obj, fn() passes nothing, fn.call(x) passes x, new Fn() passes a brand new object. Detaching a method into a variable or a callback drops the receiver, which is the single most common source of "cannot read properties of undefined". Sloppy mode hid it by substituting the global object; strict mode leaves it undefined so the failure is loud.
Arrows opt out entirely. They have no this binding, so this inside one resolves lexically, exactly like any other variable. That makes them right for callbacks written inside a method and wrong for a method itself: whoArrow reaches past the object literal into the surrounding scope, because an object literal is not a scope. The same reasoning explains the class comparison at the end. bumpField is an arrow created inside the constructor, so it captured that instance and became an own property of it; bumpMethod is a shared prototype method that needs a receiver. That is the whole argument for class fields in event handlers.
bind is one-way: it returns an exotic function with the receiver already fixed, and a second bind only wraps the wrapper, so the first one wins for ever. new is the exception that overrides even bind, because construction allocates its own this before the call.