How does this object method definition work without the “function” keyword?

后端 未结 2 1034
遥遥无期
遥遥无期 2020-11-22 04:17

I discovered this by accidentally leaving off the function keyword. Ordinarily the foobar method in the module below would be declared as fo

相关标签:
2条回答
  • 2020-11-22 04:24

    ES6 allows "concise methods" which, as you've discovered, aren't cross-browser compatible yet.

    0 讨论(0)
  • 2020-11-22 04:43

    How is it possible that this runs at all in any browser? Is is some sort of new ES6 functionality?

    Yes.

    ...

    Method definitions

    A property of an object can also refer to a function or a getter or setter method.

    var o = {
      property: function ([parameters]) {},
      get property() {},
      set property(value) {},
    };
    

    In ECMAScript 6, a shorthand notation is available, so that the keyword "function" is no longer necessary.

    // Shorthand method names (ES6)
    var o = {
      property([parameters]) {},
      get property() {},
      set property(value) {},
      * generator() {}
    };
    

    ...

    0 讨论(0)
提交回复
热议问题