WEB开发网
开发学院网页设计JavaScript Javascript中的this关键字 阅读

Javascript中的this关键字

 2010-09-14 13:23:59 来源:WEB开发网   
核心提示:In JavaScript this always refers to the “owner” of the function we're executing, or rather, to the object that a function is a method of. 这是来自ht

In JavaScript this always refers to the “owner” of the function we're executing, or rather, to the object that a function is a method of.

这是来自http://www.quirksmode.org/js/this.html这篇文章里对this的定义,直接看定义似乎什么也不知道,下面通过实例来说明各种情况下this所指代的对象以及原理。

关于js中的this关键字的文章已经不少了,我看过几篇,我写这篇文章的目的是从实例中分析出this的工作原理,希望对大家有所帮助。

一、基本的:

functiondoSomething(){
  alert(this.id);
}
alert(window.doSomething);//证明了doSomething是属于window的
doSomething();//undefined
window.onload=function(){
  document.getElementById("div2").onclick=doSomething;//div2
  document.getElementById("div3").onclick=function(){doSomething();}//undefined
}

1、对于doSomething这个函数:

functiondoSomething(){
  alert(this.id);
}

这个函数是全局函数,这种全局函数实际上是属于window的(可以通过window.doSomething来访问),如果直接调用,那么根据“this always refers to the “owner” of the function we're executing”,那么函数中的this就是window,但是window没有id属性,所以显示“undefined”;

2、在html元素中这样调用

<divid="div1"onclick="doSomething();">div1</div>

这时也会显示“undefined”,这就相当于如下代码:

1 2 3 4 5 6  下一页

Tags:Javascript this 关键字

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接