A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Functions/Method_definitions below:

方法定義 - JavaScript | MDN

方法定義

Baseline Widely available

自 ECMAScript 2015 開始,引入了一種於物件初始器(objects initializers)中定義方法的簡短語法。是一個將函式指派予方法名稱的簡便方式。

嘗試一下
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 類似。

請看以下程式碼:

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

你可以把它縮減為:

var obj = {
  foo() {
    /* code */
  },
  bar() {
    /* code */
  },
};
產生器方法

產生器方法(Generator method)也可以透過簡短語法定義之。用的時候:

// 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 方法 也可以透過簡短語法定義。

// 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.

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.

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
var obj = {
  a: "foo",
  b() {
    return this.a;
  },
};
console.log(obj.b()); // "foo"
Computed property names

The shorthand syntax also supports computed property names.

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
規範 瀏覽器相容性 參見

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4