PHP的函数里,不能直接访问函数外面的变量,除非显式地声明该变量为global。JavaScript可以直接访问:
var str = 'tom';
(function(){
str = 'jack';
})();
alert(str); //打印出jack
但是,如果在函数里重新声明变量str,结果就不同了:
var str = 'tom';
(function(){
var str = 'jack';
})();
alert(str); //打印出tom
如果在函数里定义一个变量,它在外面能被访问吗?
(function(){
var str = 'jack';
})();
alert(typeof str); //打印出 'undefined'
---------
结论
---------
在函数里,可以访问函数体外面的变量;
从函数外面,则不能访问函数体里定义的变量;
在google Ajax APIs Playground关于《Anonymous Function for Clean Namespace》的示例代码中,开头的注释如下:
/* * Javascript uses functional scope * A variable defined in a function is not available outside * Very useful for keeping global namespace clean * Hide your code in an anonymous function! * Then 3rd party Javascripts don't collide! * To export any methods to the global, assign them to the window obj (that is the global context) */
---------
意思
---------
JavaScript的函数作用域;
在函数内定义的变量不能在外面访问;
在保持全局命名空间整洁性方面非常有作用;
把你的代码放在匿名函数里!
那么,就不会和第三方的JavaScript冲突!
。。。
---------
示例
---------
/*
* Javascript uses functional scope
* A variable defined in a function is not available outside
* Very useful for keeping global namespace clean
* Hide your code in an anonymous function!
* Then 3rd party Javascripts don't collide!
* To export any methods to the global, assign them to the window obj (that is the global context)
*/
var contentDiv = document.getElementById('content');
(function() {
var a = 'Invisible outside of anonymous function';
function invisibleOutside() {
}
function visibleOutside() {
}
window.visibleOutside = visibleOutside;
var html = '--INSIDE Anonymous--';
html += '<br/> typeof invisibleOutside: ' + typeof invisibleOutside;
html += '<br/> typeof visibleOutside: ' + typeof visibleOutside;
contentDiv.innerHTML = html + '<br/><br/>';
})();
var html = '--OUTSIDE Anonymous--';
html += '<br/> typeof invisibleOutside: ' + typeof invisibleOutside;
html += '<br/> typeof visibleOutside: ' + typeof visibleOutside;
contentDiv.innerHTML += html + '<br/>';
运行结果 写道
--INSIDE Anonymous--
typeof invisibleOutside: function
typeof visibleOutside: function
--OUTSIDE Anonymous--
typeof invisibleOutside: undefined
typeof visibleOutside: function
typeof invisibleOutside: function
typeof visibleOutside: function
--OUTSIDE Anonymous--
typeof invisibleOutside: undefined
typeof visibleOutside: function
本文探讨了JavaScript中函数内外变量的访问规则,包括变量的作用域、匿名函数的使用及如何避免全局命名空间污染。
794

被折叠的 条评论
为什么被折叠?



