JS This是什么

参考资料: http://hi.baidu.com/tkocn/blog/item/7c66bd02f7395b084afb5150.htmljavascript

JavaScript:this是什么?

定义:this是包含它的函数做为方法被调用时所属的对象。
说明:这句话有点咬嘴,但一个多余的字也没有,定义很是准确,咱们能够分3部分来理解它!
一、包含它的函数。二、做为方法被调用时。三、所属的对象。
看例子:html

function to_green(){
    this.style.color = "green";
}
to_green();


上面函数中的this指的是谁?
分析:包含this的函数是,to_green
该函数做为方法被调用了
该函数所属的对象是。。?咱们知道默认状况下,都是window对象。
OK,this就是指的window对象了,to_green中执行语句也就变为,window.style.color="green"
这让window很上火,由于它并无style这么个属性,因此该语句也就没什么做用。
咱们在改一下。java

window.load = function(){
    var example = document.getElementById("example");
    example.onclick = to_green;
}


这时this又是什么呢?
咱们知道经过赋值操做,example对象的onclick获得to_green的方法,那么包含this的函数就是onclick喽,
那么this就是example引用的html对象喽。
this的环境能够随着函数被赋值给不一样的对象而改变!
下面是完整的例子:
 函数

<script type="text/javascript">
    function to_green(){
        this.style.color = "green";
    }
    function init_page(){
        var example = document.getElementById("example");
        example.onclick = to_green;
    }
    window.onload = init_page;
</script>
<a href="#" id="example">点击变绿</a>