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

柔情痞子 提交于 2019-11-26 03:14:01

问题


I discovered this by accidentally leaving off the function keyword. Ordinarily the foobar method in the module below would be declared as foobar: function(arg1), but interestingly the following works, at least in some browsers, e.g. Chrome Version 44.0.2403.157 m, but it fails in IE 11.0.9600.17959

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

var module = {
    foobar(arg1) {
        alert(arg1);
    }
};

module.foobar(\"Hello World\");

回答1:


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() {}
};

...




回答2:


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



来源:https://stackoverflow.com/questions/32404617/how-does-this-object-method-definition-work-without-the-function-keyword

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!