Path: blob/main/files/en-us/web/javascript/reference/functions/method_definitions/index.md
6520 views
------{{JsSidebar("Functions")}}
Method definition is a shorter syntax for defining a function property in an object initializer. It can also be used in classes.
{{EmbedInteractiveExample("pages/js/functions-definitions.html")}}
Syntax
Description
The shorthand syntax is similar to the getter and setter syntax.
Given the following code:
You are now able to shorten this to:
function*, async function, and async function* properties all have their respective method syntaxes; see examples below.
However, note that the method syntax is not equivalent to a normal property with a function as its value — there are semantic differences. This makes methods defined in object literals more consistent with methods in classes.
Method definitions are not constructable
Methods cannot be constructors! They will throw a {{jsxref("TypeError")}} if you try to instantiate them. On the other hand, a property created as a function can be used as a constructor.
Using super in method definitions
Only functions defined as methods have access to the super keyword. super.prop looks up the property on the prototype of the object that the method was initialized on.
Examples
Using method definitions
Method definitions in classes
You can use the exact same syntax to define public instance methods that are available on class instances. In classes, you don't need the comma separator between methods.
Public instance methods are defined on the prototype property of the class and are thus shared by all instances of the class. They are writable, non-enumerable, and configurable.
Inside instance methods, this and super work like in normal methods. Usually, this refers to the instance itself. In subclasses, super lets you access the prototype of the object that the method is attached to, allowing you to call methods from the superclass.
Static methods and private methods use similar syntaxes, which are described in the static and private class features pages.
Computed property names
The method syntax also supports computed property names.
Generator methods
Note that the asterisk (*) in the generator method syntax must be before the generator property name. (That is, * g(){} will work, but g *(){} will not.)
Async methods
Async generator methods
Specifications
{{Specifications}}
Browser compatibility
{{Compat}}