可以在对象初始值设定项中定义方法而不使用`function`关键字吗? [英] Can methods be defined in an object initializer without using the `function` keyword?
问题描述
前几天我有点累了,我写了这个JavaScript代码:
The other day I was a bit tired, I wrote this JavaScript code:
var obj = {a(toto){console.log("func a: ", toto);} };
然后我试过:
obj.a("hello");
> func a: hello
它有效。
我真正想写的是:
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?)
推荐答案
这是ECMAScript 6语法。根据您的环境 - 节点与浏览器 - 使用此语法可能会或可能不建议(例如,不支持跨浏览器)。
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(){}};
参考:
方法定义(ES6)
这篇关于可以在对象初始值设定项中定义方法而不使用`function`关键字吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!