JavaScript:从外部访问匿名函数内部的变量

JavaScript:从外部访问匿名函数内部的变量

问题描述:

假设我有这个匿名函数:

Say I have this anonymous function:

(function(window){

 var private = 'private msg';

 function sayit() {
   alert(private) // works
 }

 document.body.onclick = sayit; // works

})(window);

// private shouldn't be accessible here

这是 JavaScript 应该表现的方式吗?

Is this how JavaScript should behave?

也就是说,没有办法从匿名函数之外的任何地方访问private?

That is, there is no way to access private from anywhere outside of that anonymous function?

如果是这样,是否有可能找到某种从外部访问 private 的黑客,让代码保持原样?

If so, is it possible to find some kind of hack to access private from the outside, leaving the code the way it is?

是的,这就是 Javascript 让您拥有私有"变量(隐藏在函数作用域中)的方式.

Yes, this is how Javascript lets you have 'private' variables (hidden in a function scope).

不,在不重新编写代码的情况下,无法访问诸如 private 之类的变量.

No, there's no hack available to access variables such as private without re-writing the code.

在函数内用 var 定义的变量只能在该函数内访问.

Variables defined with var within a function can be accessed only from within that function.