【问题标题】:Why are there 2 parentheses after Function为什么函数后面有两个括号
【发布时间】:2019-10-17 06:54:01
【问题描述】:
function sample(banana)
       {return new Function('return ' + banana)() }

为什么函数后面有两个括号?

第一个括号是新创建函数的参数吗? 第二个括号有什么作用?

【问题讨论】:

  • () 调用函数
  • 他们执行函数。
  • 更好的问题是:为什么要创建一个新函数并立即调用该函数?
  • @NinaScholz 似乎就是一个例子。但是,是的,它没用。

标签: javascript function return brackets create-function


【解决方案1】:

您可以调用带括号的函数()

x = new Function('return 0');
console.log(x());


//...is same as

console.log(new Function('return 0')())

【讨论】:

    【解决方案2】:

    分步考虑可能会有所帮助:

    function sample(banana) {
    
      // Create a new function that can be invoked later
      var myNewFunc = new Function('return ' + banana)
    
      // Invoke the function
      var result = myNewFunc()
    
      return result
    
    }
    

    现在开始删除多余的步骤。

    首先返回被调用函数的结果,而不存储在单独的变量中:

    function sample(banana) {
    
      // Create a new function that can be invoked later
      var myNewFunc = new Function('return ' + banana)
    
      // Invoke the function and return the result
      return myNewFunc()
    
    }
    

    现在你可以删除存储函数的变量了:

    function sample(banana) {
    
      // Create a new function and invoke it immediately
      return new Function('return ' + banana)()
    
    }
    

    【讨论】:

      猜你喜欢
      • 2017-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-14
      • 2018-10-14
      • 2017-10-04
      • 1970-01-01
      相关资源
      最近更新 更多