Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
144 views
in Technique[技术] by (71.8m points)

javascript - 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?)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...