Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Method definition

A method definition writes a method without the function keyword or a colon. Its this value depends on how it is called.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

({ name(parameters) { /* body */ } })
({ [expression](parameters) { /* body */ } })

Use name(parameters) { ... } to define a method in an object literal or a class body. An object literal can also contain a function-valued property written as name: function(parameters) { ... }. That colon-delimited property syntax is not valid in a class body. Method names can be computed: [expression](parameters) { ... }.

Methods do not automatically bind this: in counter.add(3) it is counter, while call can supply another object. An arrow function instead captures this from its surroundings.

An ordinary method is not a constructor usable with new. The syntax also supports super.property and the async, *, async *, get, and set variants.

Examples

"use strict";
const counter = {
  value: 2,
  add(step) {
    this.value += step;
    return this.value;
  }
};
console.log(counter.add(3));
console.log(counter.add.call({ value: 10 }, 3));
console.log(counter.value);

Result

5
13
5

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources