CKTIS / JavaScript
Object literal method shorthand
Use `method() {}` to define a method directly in an object literal. The call determines `this`, but `super` starts its lookup at the prototype of the object where the method was defined.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
const key = "computed";
({ method(a, b) { /* body */ } });
({ [key](a) { /* body */ } });
({ *generate() { /* body */ }, async run() { /* body */ }, async *stream() { /* body */ } });Object method/shorthand syntax is the method(a) { … } form in an object literal: there is no colon or function keyword. It creates an own data property that is writable, enumerable, and configurable. { method } is a different shorthand: it uses an existing binding as the property value and defines no new function.
In obj.method(), this is obj. Taking the method out of the object does not bind it; use obj.method.bind(obj) if you pass it as a callback and want to preserve the receiver. An arrow function used as a property value instead takes this from its enclosing scope.
super.method() starts lookup at the current prototype of the object where the method was defined and passes the same this to the method it calls. Copying the method to another object does not change that starting point. With method: function () { … }, you cannot use super directly in that function body. A plain function expression can serve as a constructor, but new obj.method() throws a TypeError for a shorthand method.
Use [key](a) { … } for a computed key. The forms *generate(), async run(), and async *stream() define generator, async, and async generator methods respectively, each with its own body. These forms are specified in ECMAScript 2024; check support in your target runtime.
Examples
(() => {
const base = { read() { return this.value; } };
const obj = {
value: 2,
read() { return super.read() + 1; },
ordinary: function () {},
};
Object.setPrototypeOf(obj, base);
const other = { value: 9, read: obj.read };
console.log(obj.read());
console.log(other.read());
console.log(new obj.ordinary() instanceof obj.ordinary);
try {
new obj.read();
} catch (error) {
console.log(error.name);
}
})();Result
3 10 true TypeError
Both calls find `base.read` through `super`. The first uses `obj` as `this` and yields `3`; the second uses `other` and yields `10`. `true` confirms that `ordinary` created an instance, while `TypeError` shows that the shorthand method `read` is not a constructor.
Related lessons
- JavaScript · Lesson 41 · Advanced · Version: 4