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

- JavaScript | MDN

MDN Web Docs

View in English Always switch to English

Baseline

20159

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

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

js
({
  property() {},
  *generator() {},
  async property() {},
  async *generator() {},

  // 
  []() {},
  *[]() {},
  async []() {},
  async *[]() {},
})

js
const obj = {
  foo: function () {
    // 
  },
  bar: function () {
    // 
  },
};

js
const obj = {
  foo() {
    // 
  },
  bar() {
    // 
  },
};

function*async functionasync function*

TypeError

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

super

super super.prop

js
const obj = {
  __proto__: {
    prop: "foo",
  },
  notAMethod: function () {
    console.log(super.prop); // SyntaxError: 'super' keyword unexpected here
  },
};

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

js
class ClassWithPublicInstanceMethod {
  publicMethod() {
    return "hello world";
  }
  secondPublicMethod() {
    return "goodbye world";
  }
}

const instance = new ClassWithPublicInstanceMethod();
console.log(instance.publicMethod()); // "hello world"

prototype

this super this super

js
class BaseClass {
  msg = "hello world";
  basePublicMethod() {
    return this.msg;
  }
}

class SubClass extends BaseClass {
  subPublicMethod() {
    return super.basePublicMethod();
  }
}

const instance = new SubClass();
console.log(instance.subPublicMethod()); // "hello world"

static

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

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

(*) * g(){} g *(){}

js
// 
const obj = {
  g: function* () {
    let index = 0;
    while (true) {
      yield index++;
    }
  },
};

// 
const obj2 = {
  *g() {
    let index = 0;
    while (true) {
      yield index++;
    }
  },
};

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

js
// 
const obj = {
  f: async function () {
    await somePromise;
  },
};

// 
const obj2 = {
  async f() {
    await somePromise;
  },
};

js
// 
const obj = {
  f: async function* () {
    yield 1;
    yield 2;
    yield 3;
  },
};

// 
const obj2 = {
  async *f() {
    yield 1;
    yield 2;
    yield 3;
  },
};

ECMAScript 2027 LanguageSpecification
# sec-method-definitions


Web Proxy Viewer  |  New URL  |  Original Page