JavaScript中的this

 引用:http://www.cnblogs.com/qiuliang/

JavaScript中的this

      之所以选择这个问题作为在cnblogs的第一篇技术博客,源于前两天跟同事的一次讨论,做web开发几年,也认为自己的js写了不少,可真正去解释这个 东西的时候,才发现不是这么简单,花了一些时间,写了几个小demo,让我们来一探究竟。恩,以人为镜,可知得失,看来这句话是很有道理的。

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中的不同应用场景,可能还有其他的情况不一而足,以后发现了会补充进来。

posted @ 2011-07-11 16:11  藏龍老頭  阅读(201)  评论(0编辑  收藏  举报