可以帮助读取闭包内的变量吗?我知道通过使用带有 return 语句的函数我可以获得该值。
var getCounter = (function () {
var counter = 10;
return function () {return counter;}
})();
getCounter(); produces 10
有没有办法在没有返回函数的情况下访问或读取变量?
最佳答案
var getCounter = (function () {
this.counter = 10;
})();
console.log(counter);
或
var getCounter = (function () {
counter = 10;
})();
console.log(counter);
关于javascript - 如何访问闭包内的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36467996/