【问题标题】:Why the parameter goes invalid through closure? [closed]为什么参数通过闭包无效? [关闭]
【发布时间】:2021-10-16 08:39:54
【问题描述】:

根据sn-p的代码,为什么fn1不能得到最开始的参数“foo”?如果我仍然想使用闭包的形式而不是在Fn3中涉及一个新参数,是否有可能让Fn1可以访问“foo”?

const Fn1 = (txt) => {
  console.log(txt);
}

const Fn3 = (fn, num) => {
  return () => {
    fn(); // undefined
    console.log(num) // 7
  }
}

const Fn2 = Fn3(Fn1, 7);

Fn2("foo"); // undefined, 7

【问题讨论】:

  • 它需要一个你没有传递的参数。传一个? fn(num);?
  • Fn3 返回的函数对 num 有一个闭包,但 Fn1 没有,而你没有传递值,所以... txt 未定义。将fn() 更改为fn(num)
  • 非常感谢您的回答!我已经编辑了描述以澄清我的建议是在可能的情况下以某种方式使用初始参数“foo”。
  • 不是fn 未定义,而是txt 未定义:fn() txt。默认情况下,未传入的值是未定义的。您可以通过直接调用Fn1() 来模拟这一点。现在比较Fn1('testing')

标签: javascript closures


【解决方案1】:

需要传递参数:

const Fn3 = (fn, num) => {
  return (parameter) => {
    fn(parameter);
    console.log(num);
  }
}

const Fn2 = Fn3(Fn1, 7);

Fn2("foo");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-03
    • 2017-10-05
    • 2013-12-25
    • 1970-01-01
    • 2020-03-31
    • 2012-06-09
    • 2021-05-17
    相关资源
    最近更新 更多