js的作用域

本文探讨了JavaScript中函数内外变量的访问规则,包括变量的作用域、匿名函数的使用及如何避免全局命名空间污染。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值