如何从闭包中的函数内部访问闭包中的变量?

时间:2012-08-13 23:33:10

标签: javascript closures

例如:

var closure = (function(){
 var closureVariable = "Localized";

 function ReadLocal(){
  //how can I access closureVariable here?
 }
})();

2 个答案:

答案 0 :(得分:4)

只需使用closureVariable

例如:

var closure = (function(){
 var closureVariable = "Localized";

 function ReadLocal(){
  console.log(closureVariable);
 }
})();

ReadLocal是一个内部范围,局部变量在内部范围内始终可见。

答案 1 :(得分:0)

你试过这个吗?

var closure = (function(){
 var closureVariable = "Localized";

 function ReadLocal(){
  //how can I access closureVariable here?
   console.log(closureVariable);
 }
})();

closuserVariable是readLocal的全局,因此您可以访问它。