---
title: "js的作用域"
author: "muyu"
date: "2009-07-12T18:03:39Z"
tags: []
slug: "js"
draft: false
lastmod: "2009-07-12T18:31:04Z"
id: 424372
url: "https://muyu.iteye.com/blog/424372"
---

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](http://code.google.com/apis/ajax/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