javascript中this的用法

在javascript中,由于 javascript的动态性(解释执行,当然也有简单的预编译过程),this的指向在运行时才确定。在javascript中this通常指向的是我们正在执行的函数本身,或者是指向该函数所属的对象(运行时)。当我们在页面中定义了函数 doSomething()的时候,它的owner(所有者)是页面,或者是JavaScript中的window对象(或 global对象)。对于一个onclick属性,它为它所属的HTML元素所拥有,this应该指向该HTML元素。

在几种常见场景中this的变化
函数示例

function doSomething () {
   alert(this.navigator); //appCodeName
   this.value = "I am from the Object constructor";
   this.style.backgroundColor = "# 000000";
} 

1. (A)作为普通函数直接调用时,this指向window对象. 即doSomething();
2. (B)作为控件事件触发时
    1) inline event registration 内联事件注册 .将事件直接写在HTML代码中(<element onclick=”doSomething()”>), 此时this指向 window对象
    2) Traditional event registration 传统事件注册 (DHTML方式). 形如 element.onclick = doSomething; 此时this指向 element对象
    3) <element onclick=”doSomething(this)”>作为参数传递this指向element
3. (C)作为对象使用this指向当前对象。形如:new doSomething();
4. (D)使用apply 或者call方法时,this指向所传递的对象。 形如:var obj={}; doSomething.apply(obj,new Array(”nothing”); //this à obj

相关实例:

<input id="btn" type="button" value="按钮" />

window.onload=function (){
    var oBtn=document.getElementById("btn");
    function fn1(){
        alert(this); 
    }
}

A、作为普通函数直接调用时:

var oBtn=document.getElementById("btn");
function fn1(){
   alert(this);   //this指向window
}
fn1();

B、传统事件注册:oBtn.onclick=fn1;  //this指向oBtn这个input元素  注意fn1后不能跟();

C、oBtn.onclick=function (){ //fn1(this); //this指向window }

D、oBtn.onclick=function (){alert(this);  //this指向oBtn这个input元素}
E、内联事件注册:

<input type="button" value="按钮" onclick="fn1();" />  //这时this指向window
<script>
    function fn1(){
        alert(this);
    }
</script>

 

posted @ 2017-05-02 22:23  爽朗琴天  阅读(122)  评论(0)    收藏  举报