[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Functions/Method_definitions [Back]  [Original]

- JavaScript | MDN

MDN Web Docs

View in English Always switch to English

Baseline Widely available

This feature is well established and works across many devices and browser versions. Its been available across browsers since 20159.

ECMAScript 2015 objects initializers

In this article

const obj = {
  foo() {
    return "bar";
  },
};

console.log(obj.foo());
// Expected output: "bar"

var obj = {
  property( parameters ) {},
  *generator( parameters ) {},
  async property( parameters ) {},
  async* generator( parameters ) {},

  // with computed keys:
  [property]( parameters ) {},
  *[generator]( parameters ) {},
  async [property]( parameters ) {},

  // compare getter/setter syntax:
  get property() {},
  set property(value) {}
};

ECMAScript 2015 getter setter

js
var obj = {
  foo: function () {
    /* code */
  },
  bar: function () {
    /* code */
  },
};

js
var obj = {
  foo() {
    /* code */
  },
  bar() {
    /* code */
  },
};

Generator method

  • * * g(){} g *(){}
  • yield SyntaxErrorAlways use yield in conjunction with the asterisk (*).
js
// Using a named property
var obj2 = {
  g: function* () {
    var index = 0;
    while (true) yield index++;
  },
};

// The same object using shorthand syntax
var obj2 = {
  *g() {
    var index = 0;
    while (true) yield index++;
  },
};

var it = obj2.g();
console.log(it.next().value); // 0
console.log(it.next().value); // 1

Async

Async

js
// Using a named property
var obj3 = {
  f: async function () {
    await some_promise;
  },
};

// The same object using shorthand syntax
var obj3 = {
  async f() {
    await some_promise;
  },
};

Async generator methods

Generator methods can also be async.

js
var obj4 = {
  f: async function* () {
    yield 1;
    yield 2;
    yield 3;
  },
};

// The same object using shorthand syntax
var obj4 = {
  async *f() {
    yield 1;
    yield 2;
    yield 3;
  },
};

Method definitions are not constructable

All method definitions are not constructors and will throw a TypeError if you try to instantiate them.

js
var obj = {
  method() {},
};
new obj.method(); // TypeError: obj.method is not a constructor

var obj = {
  *g() {},
};
new obj.g(); // TypeError: obj.g is not a constructor (changed in ES2016)

Simple test case

js
var obj = {
  a: "foo",
  b() {
    return this.a;
  },
};
console.log(obj.b()); // "foo"

Computed property names

The shorthand syntax also supports computed property names.

js
var bar = {
  foo0: function () {
    return 0;
  },
  foo1() {
    return 1;
  },
  ["foo" + 2]() {
    return 2;
  },
};

console.log(bar.foo0()); // 0
console.log(bar.foo1()); // 1
console.log(bar.foo2()); // 2

Specification
ECMAScript 2027 LanguageSpecification
# sec-method-definitions


Web Proxy Viewer  |  New URL  |  Original Page