我应该在这两者之间使用哪一种,哪一种优于另一种?
// 1st
{ ["test"]() { return 1; } }
// 2nd
{ "test": function () { return 1; } }
"test": function () { return 1; }
是旧的方式,"test"() { return 1; }
是function
关键字被忽略的新方式。
另请注意,[]
允许您使用变量作为标识符
let name = "test1"
let a = {
"test2": function () { return "you called test2" },
"test3"() { return "you called test3" },
[name]() { return "you called test1" },
[name + "1"]() { return "you called " + name + "1" }
}
// written differently works the same
console.log( a.test2() ) // "you called test2" <-- the old way declared one
console.log( a.test3() ) // "you called test3" <-- new way declared one
// same call
console.log( a[name]() ) // "you called test1" <-- declared using
console.log( a.test1() ) // "you called test1" <-- [name]() {...}
// the [...] notation allow the build of identifier freely
console.log( a.test11() ) // "you called test11" <-- declared using
console.log( a[name + "1"]() ) // "you called test11" <-- [name + "1"]() {...}
既然Javascript像许多其他语言一样倾向于避免旧程序继续工作的弃用,那么你可以做到一件事可以做很多事情
它允许使用变量属性名称:
let propName = "test"
console.log({ [propName]() { return 1 } }.test());
好处:
{name: function() { ... }}
格式,所有函数都是匿名的,即使引用它们的属性具有名称。)名称帮助工具可帮助您显示调试器中的调用堆栈,以告诉您哪个函数引发了异常。 (2015年更新:最新的JavaScript规范,ECMAScript第6版,定义了JavaScript引擎必须推断函数名称的大量方法。其中之一就是在我们的{name: function() { ... }}
示例中将函数分配给属性时。所以当引擎实现时ES6,这个理由会消失。)internalSomething
)。页面上没有其他代码可以调用这些函数;他们真的很私密。只有您在return语句中最后导出的那些是可见的
在范围界定功能之外。