Named function inside a Javascript object? Why does this work?

922 Views Asked by At

I stumbled upon this by accident when writing some code:

var obj = {
  myFunc() {
    document.body.innerHTML = 'Hello World!';
  }
};

obj.myFunc();

What I meant to type was this:

var obj = {
  myFunc: function() { 
    // ...
  }
};

I didn't notice I accidentally typed the first one until I realized my code wasn't running in IE11.

Why does the first example work in Chrome/Firefox, and not IE11?

Also, if this is an official language feature, what is this called?

1

There are 1 best solutions below

0
On BEST ANSWER

It's an Enhanced Object Literal, which is es6 syntax. More formally, Object Initializers allow Method Definitions instead of only key/value pairs as in previous versions.

This table tells the compatibility story under 'object literal extensions'. The short answer is just that IE11 hasn't implemented that feature.