如何在闭包内访问变量

时间:2016-04-07 06:11:08

标签: javascript closures

可以帮助读取闭包内的变量。我知道通过使用return语句的函数我可以得到值。

var getCounter = (function () {
    var counter = 10;
    return function () {return counter;}
})();

getCounter(); produces 10

有没有办法在没有返回功能的情况下访问或读取变量?

3 个答案:

答案 0 :(得分:1)

var getCounter = (function () {
    this.counter = 10;
})();

console.log(counter);

var getCounter = (function () {
        counter = 10;
    })();

    console.log(counter);

jsfiddle

答案 1 :(得分:0)

我不知道为什么你需要一个闭包,

var getCounter = (function () {
  counter = 10;
  return counter;
})();
// As you wrote a closure it is self executed so getCounter variable has the counter value; 
var x = getCounter; 

答案 2 :(得分:0)

你也可以尝试这个,

var counter;
var getCounter = (function() {
  counter = 10;
})();