[英]how to access variable inside the closure
可以幫助讀取封閉中的變量。 我知道通過具有帶有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);
我不知道為什么你需要在這里關閉
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;
您也可以嘗試一下
var counter; var getCounter = (function() { counter = 10; })();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.