javascript命名对象中的函数

问题描述 投票:0回答:3

我应该在这两者之间使用哪一种,哪一种优于另一种?

// 1st
{ ["test"]() { return 1; } }

// 2nd
{ "test": function () { return 1; } }
javascript
3个回答
5
投票

"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像许多其他语言一样倾向于避免旧程序继续工作的弃用,那么你可以做到一件事可以做很多事情


1
投票

它允许使用变量属性名称:

let propName = "test"
console.log({ [propName]() { return 1 } }.test());

1
投票

好处:

  • 函数声明正常,因此具有名称。 (尽管使用{name: function() { ... }}格式,所有函数都是匿名的,即使引用它们的属性具有名称。)名称帮助工具可帮助您显示调试器中的调用堆栈,以告诉您哪个函数引发了异常。 (2015年更新:最新的JavaScript规范,ECMAScript第6版,定义了JavaScript引擎必须推断函数名称的大量方法。其中之一就是在我们的{name: function() { ... }}示例中将函数分配给属性时。所以当引擎实现时ES6,这个理由会消失。)
  • 使您可以自由地使用仅由模块使用的私有函数(例如上面的internalSomething)。页面上没有其他代码可以调用这些函数;他们真的很私密。只有您在return语句中最后导出的那些是可见的 在范围界定功能之外。
  • 如果实现完全改变(例如IE-vs-W3C内容,或SVG与Canvas等),则可以根据环境轻松返回不同的功能。
© www.soinside.com 2019 - 2024. All rights reserved.