在JavaScript中,如何从外部增加函数内部的变量?

时间:2017-09-09 10:43:43

标签: javascript

我已尝试在函数外声明变量,但我得到了未定义。

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

        return bar;
        }

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

1 个答案:

答案 0 :(得分: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/