Javascript中的关键字this

本文通过六个示例详细解析了JavaScript中this关键字的行为表现,包括全局函数、对象实例化、原型链扩展、闭包函数及HTML事件处理中的this指向规则。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这篇博客不是自己写的,转自:http://www.cnblogs.com/qiuliang/archive/2011/04/27/2030367.html,有兴趣的童鞋可以访问本文原博客哦

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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值