首页 > 解决方案 > 使函数使用对象作为其作用域

问题描述

假设我有这样的代码:

var opts = {hello: "it's me", imusthavetried: "a thousand times"}
function myFunction (options) {
}
myFunction(opts)

有什么办法可以让它myFunction只写hello而不是options.hello?我知道我可以遍历每个选项对象子对象并重新定义它们,但是有没有办法自动将选项对象用作函数的范围?

标签: javascriptobjectscope

解决方案


您可以使用with块,但通常不赞成使用它(如MDN 文档中所述)。过去它会导致性能问题,但在现代版本的 V8 引擎(谷歌 Chrome 和 Node.js 使用的引擎)中已经修复了这个问题。

function myFunction(options) {
  with(options) {
    console.log(hello);
  }
}

myFunction({ hello: 'Hello, World!' });


推荐阅读