简体   繁体   English

如何在闭包内部访问变量

[英]how to access variable inside the closure

Can some help on to read the variables inside the closures. 可以帮助读取封闭中的变量。 I know by having a function with return statement i can get the value. 我知道通过具有带有return语句的函数,我可以获得值。

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

getCounter(); produces 10

Is there any way to access or read the variable without the return function ? 没有返回函数,有没有办法访问或读取变量?

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

console.log(counter);

or 要么

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

    console.log(counter);

jsfiddle jsfiddle

I dont know why you need a closure here, 我不知道为什么你需要在这里关闭

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; 

You can also try this, 您也可以尝试一下

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM