【问题标题】:Pass input parameters to returned JS functions将输入参数传递给返回的 JS 函数
【发布时间】:2021-06-29 11:32:46
【问题描述】:

我试图在 return 语句中将输入参数从一个函数传递到另一个函数。但是在下面的示例中 input1 和 input2 是未定义的。 return 语句中的值是未定义的,而在工厂函数中它们不是。如何将值传递给返回的 func()?

   function func(input1,input2) {
     console.log(input1,input2)
     // "undefined, undefined"
   }
    
    angular.module("factory").factory("test", (input1, input2) => {
     console.log(input1, input2)
     //"input1", "input2"
        return {
            func: (input1, input2) => {
                func(input1, input2);
            }
        };
    });

【问题讨论】:

  • 您返回的func() 方法 有自己的input1input2,它们会影响父函数的input1input2。如果方法不需要参数,只需删除它们,func 函数将使用外部参数。
  • func : 函数中的 input1 与其外部不同。这是一个本地参数。您可以在定义中省略 input1 和 input2。

标签: javascript


【解决方案1】:

这一行:

func: (input1, input2) => {

shadows 外部函数的参数(通过声明它自己的同名参数)。所以只需删除那些。例如

angular.module("factory").factory("test", (input1, input2) => {
    return {
        func: () => {
            func(input1, input2);
        }
    };
});

【讨论】:

    【解决方案2】:

    func : 函数里面的 input1 和 input2 和外面的不一样。它们是本地参数,将在函数调用时传递。您可以从定义中省略 input1 和 input2 并像这样调用函数func()

    console.log(input1, input2)
         //"input1", "input2"
            return {
                func: () => {        
                   func(input1, input2);
                }
            };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-06-10
      • 2021-08-28
      • 2014-08-16
      • 2013-08-08
      • 1970-01-01
      • 2020-12-23
      • 1970-01-01
      相关资源
      最近更新 更多