JavaScript:从外部访问匿名函数内部的变量 [英] JavaScript: access variables inside anonymous function from the outside

查看:55
本文介绍了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.

这篇关于JavaScript:从外部访问匿名函数内部的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆