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?)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With