---
title: "javascript中的this到底指什么？ "
author: "sntetwt"
date: "2011-09-19T18:35:47Z"
tags: []
categories: ["Web前端"]
slug: "javascript-this"
draft: false
lastmod: "2011-09-19T18:35:47Z"
id: 1175351
url: "https://sntetwt.iteye.com/blog/1175351"
---

```
JavaScript：this 是什么？

定义：this是包含它的函数作为方法被调用时所属的对象。
说明：这句话有点咬嘴，但一个多余的字也没有，定义非常准确，我们可以分3部分来理解它！
    1、包含它的函数。2、作为方法被调用时。3、所属的对象。
看例子：
```

```
function to_green(){
```

&lt;!--CRLF--&gt;

```
   this.style.color="green";
```

&lt;!--CRLF--&gt;

```
}
```

&lt;!--CRLF--&gt;

```
to_green();
```

&lt;!--CRLF--&gt;

```
上面函数中的this指的是谁？
分析：包含this的函数是，to_green
     该函数作为方法被调用了
      该函数所属的对象是。。？我们知道默认情况下，都是window对象。
OK，this就是指的window对象了，to_green中执行语句也就变为，window.style.color="green"
这让window很上火，因为它并没有style这么个属性，所以该语句也就没什么作用。
我们在改一下。
```

```
window.load=function(){
```

&lt;!--CRLF--&gt;

```
    var example=document.getElementById("example");
```

&lt;!--CRLF--&gt;

```
    example.onclick=to_green;
```

&lt;!--CRLF--&gt;

```
}
```

&lt;!--CRLF--&gt;

```
这时this又是什么呢？
我们知道通过赋值操作，example对象的onclick得到to_green的方法，那么包含this的函数就是onclick喽，
那么this就是example引用的html对象喽。
this的环境可以随着函数被赋值给不同的对象而改变！
下面是完整的例子：
```

```
<script type="text/javascript">
```

&lt;!--CRLF--&gt;

```
     function to_green(){
```

&lt;!--CRLF--&gt;

```
        this.style.color="green";
```

&lt;!--CRLF--&gt;

```
    }
```

&lt;!--CRLF--&gt;

```
    function init_page(){
```

&lt;!--CRLF--&gt;

```
    var example=document.getElementById("example");
```

&lt;!--CRLF--&gt;

```
        example.onclick=to_green;
```

&lt;!--CRLF--&gt;

```
   }
```

&lt;!--CRLF--&gt;

```
   window.onload=init_page;
```

&lt;!--CRLF--&gt;

```
</script>
```

&lt;!--CRLF--&gt;

```
<a href="#" id="example">点击变绿</a>
```