CKTIS / JavaScript
Method definition shorthand
Use `name(p) { … }` to define a method without a colon or the `function` keyword. The call supplies `this`, while the definition determines where `super` starts looking up properties.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
const obj = {
method(p) { /* body */ },
};
class Example {
method(p) { /* body */ }
static method(p) { /* body */ }
}Method definition shorthand uses name(p) { … } in an object literal to create an own property named name whose value is a function. Separate object literal properties with commas, but do not put commas between class methods. A public instance method is defined on the class prototype; a public static method is defined on the class itself.
In obj.name(x), this is obj. The syntax does not bind this permanently: if you extract the method, you can still supply this explicitly with call. By contrast, an arrow function written as name: (p) => … uses this from its enclosing scope.
Inside a method, super.name starts the lookup at the current prototype of the object on which the method was defined. Copying the function to another object does not change that starting object's identity. In super.name(), the method found by the lookup receives the current this.
The form name: function (p) { … } also creates a function-valued property, but that function cannot use super.name directly in its body. An ordinary method is not a constructor: new obj.name() throws a TypeError. A class's special constructor definition follows different rules. Do not confuse method shorthand with property shorthand { name }, which uses an existing binding named name. ECMAScript 2024 specifies the syntax; check support if you target older runtimes.
Examples
{
const base = {
total() { return this.amount; },
};
const item = {
amount: 10,
total(extra) { return super.total() + extra; },
};
Object.setPrototypeOf(item, base);
console.log(item.total(2));
console.log(item.total.call({ amount: 20 }, 2));
}Result
12 22
`Object.setPrototypeOf(item, base)` sets `base` as the prototype of `item`. In the first call, `this.amount` is `10`, so the result is `12`. The second call uses `call` to supply a `this` with `amount: 20`, but `super.total()` still finds the method on `base`. The result is `22`.
Related lessons
- JavaScript · Lesson 12 · Intermediate · Version: 3