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

查看:126
本文介绍了JavaScript:从外部访问匿名函数内的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有这个匿名函数:

 (函数(窗口){

var private ='private msg';

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

document.body.onclick = sayit ; //工作

})(窗口);

//私人不应该在这里访问

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



也就是说,无法从该匿名函数之外的任何地方访问 private ? / p>

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

解决方案

是的,这就是Javascript让你拥有'私有'变量(隐藏在函数范围内)的方式。



不,没有黑客可以访问变量,例如 private ,而无需重新编写代码。



函数中使用 var 定义的变量只能在该函数中访问。


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

Is this how JavaScript should behave?

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

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

解决方案

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

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

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

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

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