---
title: "Javascript变量作用域问题"
author: "deng131"
date: "2010-12-01T10:49:08Z"
tags: []
categories: ["Web前端"]
slug: "javascript"
draft: false
lastmod: "2011-01-03T09:07:44Z"
id: 830175
url: "https://thinking80s.iteye.com/blog/830175"
---

<span style="color:blue">
JavasScript中变量词法作用域：也叫做静态作用域，变量的作用域是在定义时决定而不是执行时决定。即词法作用域取决于源码，通过静态分析就能确定。
</span>

```java
function f(){ 
 var t = 'a';
 return function fn(){
  alert(t)
  alert(this.t);
  var t = 123;
  alert(t);
  alert(this.t); //this == window对象
 };
}

f()()
```



```java
fn = {
 a: 1,
 b: function(){
    console.info(a);
    console.info(this.a);
 },
 c: function(){
    var t = 1;
    var _this = this; 
    //var a = 1; //local scope (1)
    //a = 123;  //golble scope (2)
    return function(){
        console.info(t);     //闭包scope情况    
        //this == window对象,当(1)处放开时this.a返回undefined,(2)放开时返回123
        console.info(this.a) 
        console.info(_this.a)
    }
 }
};

fn.c()()
```

<span style="color:darkblue">在执行Test()时，此时的上下文对象是window，即Javascript的全局对象,在执行new Test();时新建了一个Object，此时执行Test函数的上下文对象就是Object。</span>

```java
function Test() {
    console.log(this);
}
Test();    //window
new Test();//Object
```


参考：
<http://www.jb51.net/article/25248.htm>
<http://mzhou.me/?p=81001#more-81001>