【问题标题】:Make function use an object as its scope使函数使用对象作为其作用域
【发布时间】:2018-10-28 01:04:24
【问题描述】:

假设我有这样的代码:

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

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

【问题讨论】:

  • “只能写 hello 而不是 options.hello”是什么意思?
  • with(options) {alert(hello);}
  • 你的意思是在myFunction里面做console.log(options['hello'])?这应该记录'its me'
  • @VincentNguyen 不,@NiettheDarkAbsol 回答了我的问题。我的意思是你可以在不写options 或显式地为hello 赋值的情况下执行console.log(hello)
  • @NiettheDarkAbsol 但如果 hello 是在外部定义的,它会返回那个值,对吧?

标签: javascript object scope


【解决方案1】:

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

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

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

【讨论】:

  • 是否在“use: strict”中禁用?另外,如果hello是在外部定义的,会不会用hello代替options.hello
  • @BenGubler 是的,它在严格模式下被禁用。不,它总是更喜欢使用options.hello
  • 在严格模式下是否有任何等价物?
  • @BenGubler 在严格模式下没有等价物。
【解决方案2】:
var opts = {hello: "it's me", imusthavetried: "a thousand times"}
function myFunction (options) {
    with( options ) {
        console.log( hello ); // "it's me"
    }
}
myFunction(opts)

【讨论】:

    【解决方案3】:

    另一种选择是将“this”对象绑定到您的对象:

    var opts = {hello: "it's me", imusthavetried: "a thousand times"}
    function myFunction (options) {
      console.log(this.hello)
    }
    
    myFunction = myFunction.bind(opts);
    myFunction();

    【讨论】:

      猜你喜欢
      • 2020-11-20
      • 2020-02-12
      • 1970-01-01
      • 1970-01-01
      • 2011-10-25
      • 2013-09-11
      • 2014-10-01
      • 2018-08-04
      • 2012-08-31
      相关资源
      最近更新 更多