以人为镜,可知得失,看来这句话是很有道理的。

Demo 1 :
如果是一个全局的function,则this相当于window对象,在function里定义的各种属性或者方法可以在function外部访问到,前提是这个function需要被调用。

代码如下:

<script type="text/javascript"> 
//在function中使用this 
function a() { 
if (this == window) { 
alert("this == window"); 
this.fieldA = "I'm a field"; 
this.methodA = function() { 
alert("I'm a function "); 
} 
} 
} 
a(); //如果不调用a方法,则里面定义的属性会取不到 
alert(window.fieldA); 
methodA(); 
</script>

Demo 2 :
如果使用new的方式去实例化一个对象,则this不等于window对象,this指向function a的实例

代码如下:

<script type="text/javascript"> 
//在function中使用this之二 
function a() { 
if (this == window) { 
alert("this == window"); 
} 
else { 
alert("this != window"); 
} 
this.fieldA = "I'm a field"; 
} 
var b = new a(); 
alert(b.fieldA); 
</script>

Demo 3 :
使用prototype扩展方法可以使用this获取到源对象的实例,私有字段无法通过原型链获取

代码如下:

<script type="text/javascript"> 
//在function中使用this之三 
function a() { 
this.fieldA = "I'm a field"; 
var privateFieldA = "I'm a var"; 
} 
a.prototype.ExtendMethod = function(str) { 
alert(str + " : " + this.fieldA); 
alert(privateFieldA); //出错 
}; 
var b = new a(); 
b.ExtendMethod("From prototype"); 
</script>

Demo 4 :
不管是直接引用function,还是实例化一个function,其返回的闭包函数里的this都是指向window

代码如下:

<script type="text/javascript"> 
//在function中使用this之四 
function a() { 
alert(this == window); 
var that = this; 
var func = function() { 
alert(this == window); 
alert(that); 
}; 
return func; 
} 
var b = a(); 
b(); 
var c = new a(); 
c(); 
</script>

Demo 5 :
在HTML中使用this,一般代表该元素本身

代码如下:

<div onclick="test(this)" id="div">Click Me</div> 
<script type="text/javascript"> 
function test(obj) { 
alert(obj); 
} 
</script>

Demo 6 :
在IE和火狐(Chrome)下注册事件,this分别指向window和元素本身

代码如下:

<div id="div">Click Me</div> 
<script type="text/javascript"> 
var div = document.getElementById("div"); 
if (div.attachEvent) { 
div.attachEvent("onclick", function() { 
alert(this == window); 
var e = event; 
alert(e.srcElement == this); 
}); 
} 
if (div.addEventListener) { 
div.addEventListener("click", function(e) { 
alert(this == window); 
e = e; 
alert(e.target == this); 
}, false); 
} 
</script>

以上就是我总结的this在javascript中的不同应用场景,可能还有其他的情况不一而足,以后发现了会补充进来。