29

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");
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Dexygen
  • 12,287
  • 13
  • 80
  • 147

2 Answers2

30

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

...

2540625
  • 11,022
  • 8
  • 52
  • 58
user229044
  • 232,980
  • 40
  • 330
  • 338
  • As you can see though, in the first case, `new o.preperty()` behaves normally. Using shorthand method names, `new o.property()` throws an error. See [here](http://stackoverflow.com/questions/41193117/constructor-behaving-differently-using-es6-shorthand-notation) – nicovank Jan 09 '17 at 16:46
13

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

Joseph
  • 117,725
  • 30
  • 181
  • 234