【问题标题】:Function Expression (JavaScript)函数表达式 (JavaScript)
【发布时间】:2023-02-17 23:39:38
【问题描述】:

将名为 functionDeclaration 的函数转换为匿名函数表达式并将其分配给名为 myFunc 的变量。

function functionDeclaration() {
  let myFunc = str
   return "Hi there!";

}

console.log(myFunc())

我是编码新手。我究竟做错了什么?它应该打印“你好!”但一直给我参考错误信息。

感谢您的帮助!

【问题讨论】:

  • myFuncfunctionDeclaration 的本地地址,您无法在上述功能之外访问它。另外,str 突然冒出来,如果你运行这个函数会导致错误。我想你误解了这个任务,它要求你创建一个变量,它的值是一个函数。

标签: javascript


【解决方案1】:

你的函数表达式可能是这样的,

const func = function functionDeclaration() {
    return "Hi there!";
 }
 
 let myFunc = func()
 console.log(myFunc);

【讨论】:

    【解决方案2】:

    我不确定 let myFunc = str 的目的是什么,但试试这个 -

    function functionDeclaration() {
      // let myFunc = str
      return "Hi there!";
    }
    
    const myFunc = () => {
      return functionDeclaration.call(this);
    }
    
    console.log(myFunc());
    

    【讨论】:

      【解决方案3】:

      您的答案:

      let myFunc = function() {
          return "Hi there!";
      }
      

      请阅读Constructor vs. declaration vs. expression

      【讨论】:

        【解决方案4】:

        它与:

        const func = function() {
          return `Hi there!`
        }
        console.log(func())
        
        let myfunc = func
        console.log(myfunc())
        
        const func1 = function(name) {
          return `Hi my name is ${name}!`
        }
        console.log(func1('abc'))
        
        let myfunc1 = func1
        console.log(myfunc1('xyz'))
        
        myfunc = func1
        
        console.log(myfunc('123'))

        【讨论】:

          【解决方案5】:

          函数函数声明(){ 返回“你好!” }

          const myFunc = functionDeclaration; 控制台日志(myFunc())

          【讨论】:

          • 您的答案可以通过其他支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写出好的答案的信息in the help center
          【解决方案6】:

          假设 functionDeclaration 定义如下:

          function functionDeclaration() {
             return "Hi there!";
          }
          

          这是一个函数表达式:

          const myFunc = () => {
             return "Hi there!";
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2017-07-08
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-05-16
            • 2014-05-23
            • 2013-12-14
            相关资源
            最近更新 更多