JavaScriptFundamental (ES6), part 1
The __proto__ key in object literals in JavaScript
77 Computed keys, shorthand, and the __proto__ that is not a key
fairBuild an object whose keys come from variables and expressions, add a shorthand property and a shorthand method, and hide one entry behind a symbol. Then show two traps: an arrow written as a method has no this to use, and __proto__ written plainly in a literal sets the prototype instead of becoming a key.
Stuck? Three hints, smallest first
- 1. Anything in
[ ]is evaluated and coerced to a string key, unless it is a symbol. - 2. A shorthand method gets its own
this; an arrow in the same position takesthisfrom the surrounding scope, which in a strict module isundefined. - 3.
{ __proto__: x }is a special form in an object literal.{ ['__proto__']: x }is not.
const field = 'lga';
const zone = 'B';
const idKey = Symbol('id');
const stall = {
[field]: 'Ikeja',
[`zone${zone}`]: true,
zone,
[1 + 1]: 'row two',
[idKey]: 4417,
describe() {
return `${this[field]} zone ${this.zone}`;
},
arrowDescribe: () => `${this === undefined ? 'no this' : 'has this'}`,
};
const keys = Object.keys(stall);
const described = stall.describe();
const arrowSaw = stall.arrowDescribe();
const brokenArrow = { name: 'Yaba', label: () => `stall ${this?.name}` };
const brokenSaid = brokenArrow.label();
const symbolIsHidden = [keys.includes('id'), JSON.stringify(stall).includes('4417')];
const symbolIsReachable = [stall[idKey], Object.getOwnPropertySymbols(stall).length];
const last = 'takings';
const duplicated = { [last]: 1, [last]: 2, takings: 3 };
const special = { __proto__: null, good: 'garri' };
const computed = { ['__proto__']: null, good: 'garri' };
const prototypes = [Object.getPrototypeOf(special), Object.getPrototypeOf(computed) === Object.prototype];
const computedOwnsIt = Object.keys(computed);
console.log('keys :', keys, '| numeric key:', stall[2]);
console.log('methods:', described, '| arrow:', arrowSaw, brokenSaid);
console.log('symbol :', symbolIsHidden, symbolIsReachable);
console.log('proto :', prototypes, computedOwnsIt);
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('a computed key can come from a variable or from any expression', keys, ['2', 'lga', 'zoneB', 'zone', 'describe', 'arrowDescribe']);
test('a number in brackets becomes a string key, and sorts first', [stall[2], stall['2']], ['row two', 'row two']);
test('shorthand copies the variable name, and a shorthand method has its own this', [stall.zone, described], ['B', 'Ikeja zone B']);
test('an arrow in the same slot sees the enclosing this, which here is undefined', [arrowSaw, brokenSaid], ['no this', 'stall undefined']);
test('a symbol key is invisible to keys and to JSON', symbolIsHidden, [false, false]);
test('but it is a perfectly ordinary own property if you hold the symbol', symbolIsReachable, [4417, 1]);
test('a repeated key is not an error: the last one written wins', duplicated.takings, 3);
test('plain __proto__ in a literal sets the prototype instead of adding a key', prototypes, [null, true]);
test('computed __proto__ is just a key, so the object keeps its prototype', computedOwnsIt, ['__proto__', 'good']);
Computed keys turn an object literal into something you can build from data, and they are evaluated in order, so a later duplicate quietly overwrites an earlier one. Anything that is not a symbol is coerced with String(), which is why [1 + 1] becomes "2" and lands at the front of the key order along with the other integer-like keys.
Shorthand methods and arrow properties look interchangeable and are not. A method gets this from the call, so stall.describe() sees the stall. An arrow captures this from where it was written, which inside a module or a panel running in strict mode is undefined — so this?.name is the only thing keeping the second example from throwing. Arrows are the right choice for a callback that must remember its surroundings, and the wrong choice for a method on the object you are defining.
__proto__ in a literal is a genuine wart. Written plainly it is a directive to set the prototype, so { __proto__: null } is the shortest way to get a bag with no inheritance; written as a computed key or a quoted-then-computed key it is an ordinary property. That difference is the root of a whole family of prototype-pollution bugs, and it is the reason parsers and merge helpers treat the name as reserved.