CKTIS / JavaScript
Object method definitions
Write `name(a) {}` to define a method in an object literal. Learn how the call sets `this`, where `super` starts its lookup, and why the method cannot be used with `new`.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
({
name(a, b) {},
[key](a) {},
*generate() {},
async load() {},
async *stream() {},
get value() {},
set value(next) {},
})Object method definitions use syntax such as name(a) {} in an object literal to create an own data property whose value is a function. That property is writable, enumerable, and configurable. Separate definitions with commas. In [key](a) {}, the expression key is evaluated when the object is created to determine the property key. Public instance methods in a class use similar syntax but are non-enumerable properties on the class prototype.
In obj.name(), this is obj. Extracting the method does not bind it: after const f = obj.name, a plain f() has this set to undefined if the method itself is strict. A non-strict method instead uses the global this value in that call, even if the caller is strict. Use f.call(obj) to supply the receiver explicitly. By contrast, name: () => {} stores an arrow function, which takes this from its surrounding scope.
super.name() starts its lookup at the current prototype of the object where the method was defined and passes along the current this. Copying the method or using call does not change which object's prototype is used for that lookup. Unlike name: function () {} with a normal, non-async, non-generator function, a shorthand method supports super property access but is not a constructor: new obj.name() throws a TypeError.
*generate() returns a generator, async load() returns a Promise, and async *stream() returns an async generator. get value() and set value(next) define accessors rather than function-valued data properties: reading invokes the getter, which takes no parameters, and assigning invokes the setter, which takes one parameter.
Examples
{
const base = {
score() {
return this.points;
},
};
const player = {
__proto__: base,
points: 10,
["score"](bonus) {
return super.score() + bonus;
},
};
console.log(player.score(2));
console.log(player.score.call({ points: 20 }, 2));
try {
new player.score(2);
} catch (error) {
console.log(error instanceof TypeError);
}
}Result
12 22 true
`__proto__: base` sets the prototype in the literal. Both calls find `base.score` through `super` but read `points` from different receivers, giving `12` and `22`. The `true` shows that attempting construction with `new` throws a `TypeError`.
Related lessons
- JavaScript · Lesson 1 · Advanced · Version: 4
- JavaScript · Lesson 4 · Advanced · Version: 4
- JavaScript · Lesson 43 · Intermediate · Version: 3