【问题标题】:In JavaScript, how can I increment a variable that is inside a function from the outside?在 JavaScript 中,如何从外部增加函数内部的变量?
【发布时间】:2017-09-09 10:43:42
【问题描述】:

我尝试在函数外部声明变量,但未定义。

      function scope() {
      let foo = 1;
      const bar = function() {
       return ++foo;
        }

        return bar;
        }

      const baz = scope();
      console.log(baz.foo);
      console.log(baz.foo);

【问题讨论】:

标签: javascript


【解决方案1】:

这是一种方法,模块模式:

var Module = (function () {
//empty object
    var my = {};
//value
    my.value = 1;

  //method for incrementing the value 
    my.increment = function () {
        this.value++;
    };

    return my;
}());

Module.increment(); //increment the value from outside
console.log(Module.value) //log the new value

jsfiddle:https://jsfiddle.net/9dr9xy23/5/

【讨论】:

  • 好答案,但在你的小提琴中,Module.moduleProperty 需要更改为 Module.value
猜你喜欢
  • 2017-06-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-31
  • 2022-11-27
  • 2012-10-14
  • 2020-03-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多