【问题标题】:cannot understand behavior of revealing module无法理解显示模块的行为
【发布时间】:2021-01-03 18:54:17
【问题描述】:

我正在研究闭包和揭示模块模式。在我看来,我明白了,但后来在练习中我发现了这个奇怪的“错误”。 代码如下:

    const module=(function(){
    let counter=1;
  let incrCounter=function(){
  counter++;
  console.log(counter)
  }
  return { counter, incrCounter}
})();

module.incrCounter(); ///expected:2; output:2;
module.incrCounter(); ///expected:3; output:3
module.incrCounter(); ///expected:4 output:4

module.counter=1; 
module.incrCounter(); ///expected:2; output:5
module.counter; ///expected:5 (for some reason) ; output:1

我重读了关于闭包的“你不懂 JS”。它必须工作!我返回一个带有属性“counter”的对象,所以我应该可以直接访问它。但似乎我创建了一个新的同名局部变量,而不是更新我想要的计数器。我在这里做错了什么?

【问题讨论】:

  • 函数外部无法访问内部计数器变量,“module.counter=1”也无法访问内部变量。您正在正确理解闭包。

标签: javascript closures revealing-module-pattern


【解决方案1】:

当您执行return {counter, incrCounter} 时,您是在说:

  • 将counter的值复制到返回对象的counter属性中
  • 然后将incrCounter的值复制到返回对象的incrCounter属性中

您不是说要公开内部计数器变量,这意味着对module.counter 的修改只是修改副本,而不是实际值。您可以通过将其存储在对象中来解决此问题:

const module = (function() {
    let ret = {counter: 1};
    let incrCounter = function() {
        ret.counter ++;
        console.log(ret.counter);
    };
    ret.incrCounter = incrCounter;
    return ret;
})();

或者,只使用对象和this:

const module = {
    counter: 1,
    incrCounter() {
        this.counter ++;
        console.log(this.counter);
    }
};

【讨论】:

  • 哦,所以我传递的是副本,而不是指向真实计数器的指针。知道了。谢谢
猜你喜欢
  • 2022-01-21
  • 2020-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-08
  • 1970-01-01
相关资源
最近更新 更多