javascript中this关键字之我见

本文深入探讨了JavaScript中this关键字的使用与含义,通过实例分析全局函数、事件处理函数及非事件函数中this指向的不同情况,揭示其指向的对象与上下文的关系。

javascript中的this关键字是个很令人头疼的问题,学习的时候也是个难点,觉得这个东西很玄乎,很乱;

下面是我个人的一点观点:

首先我们来看看直接定义的全局函数:

function introduce() {
     alert("Hello, I am limeng");
}

这个函数的this指向谁呢?

定义在全局的函数,其实也就是window对象的一个方法,函数的所有者就是当前页面,也就是window对象,我们alert一下看看:

var name = "Hello, I am limeng";
function introduce() {
     alert(this.name);
}
window.onload = introduce; 

/*out:
  *Hello, I am limeng
  */

我们在alert一下:

var name = "Hello, I am limeng";
function introduce() {
     alert(this.name);
}

alert(window.introduce); 

/*out:
  *function introduce() {
  *   alert(this.name);
  *}
  */

很显然,跟我们预期的一样。

下面我们看看事件处理函数:

<input id="name" type="button" value="limeng" />
function showValue() {
     alert(this.value);
}
window.onload = function(){
 document.getElementById('name').onclick = showValue;
} 

/*out:
  *limeng

  */

此时的全局函数中的this为什么不是window了呢?

其实在对onclick绑定的时候, 其实是对id为name的输入框Dom对象的onclick属性的赋值。而onclick的所有者就是这个dom对象。

再看:

function showValue() {
     alert(this.value);
}
window.onload = function(){
 document.getElementById('name').onclick = showValue;
 alert(document.getElementById('name').onclick);
} 

 /*out:
  *function showValue() {
  *  alert(this.value);
  *}

  */

所以,当事件触发的时候,就会去调用name按钮的onclick方法,,这个时候this关键字自然就指向的是name按钮了。

即:对象的方法中this指的就是该对象。

再看:

<input id="name" type="button" value="limeng" onclick="showValue();" />

此处出错了,为什么呢?

因为这个时候并不是赋值,而是引用。我们弹出一下onclick看看:

alert(document.getElementById('name').onclick);

 /*out:
  *function onclick() {
  *  showValue();
  *}

  */

应该能明目为什么会了吧。

而对于不是事件处理函数的场合,我们可以使用apply,或者call,来改变this关键字的指向。

不过本人目前对apply和call了解的还不够多。简单说一个例子吧:

 var limeng = {
     name : 'limeng',
     age  : 26
 };
 
 function introduce() {
     alert(this.name);
 }

 introduce.call(limeng);

 

转载于:https://my.oschina.net/1067377855/blog/412164

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值