Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can methods be defined in an object initializer without using the `function` keyword?

The other day I was a bit tired, I wrote this JavaScript code:

var obj = {a(toto){console.log("func a: ", toto);} };

then I tried:

obj.a("hello");
> func a:  hello

And it worked.

What I really meant to write was:

var obj = {a: function(toto){console.log("func a: ", toto);} };

So my question is: why does the first code work?

Is there a doc somewhere that explains it, and do you think I can use it? (will it work in all browsers?)

like image 522
Francis Avatar asked Jan 08 '23 00:01

Francis


1 Answers

This is ECMAScript 6 syntax. Depending on your environment - node vs browser - it may or may not be advisable to use this syntax (e.g. not supported cross browser).

Given the following code:

var obj = { foo: function() {}, bar: function() {} };

You are now able to shorten this to:

var obj = { foo() {}, bar() {} };

Reference: Method definitions (ES6)

like image 79
Adam Avatar answered Jan 17 '23 20:01

Adam