Js this关键字

Posted 小欣子

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Js this关键字相关的知识,希望对你有一定的参考价值。

1.this在最外围表示的是window,他们都是一个对象,是Js里最大的对象,最外围的对象

alert(this);            //[object Window]
alert(window)            //[object Window]
alert(typeof window)      //object
alert(typeof this)      //object,这个时候的window就是this

2.全局变量也是window下的属性

var color=红色;            //这里的color是全局变量,也是window的属性,类似与this.color,window.color

3.this局部变量

var box={
    color:红色,                //对象内的变量为局部变量,也是box下的属性
    sayColor:function(){
        return this.color;        //这里的this,代表的为box对象
    }
}
var color=蓝色                    //全局变量
alert(this.color);               //蓝色,这里代表的是window,它没有在对象或者方法内
alert(box.sayColor())            //红色,打印局部的color

 

以上是关于Js this关键字的主要内容,如果未能解决你的问题,请参考以下文章