博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

javascript this的用法

Posted on 2009-03-24 13:09  懒人ABC  阅读(238)  评论(2编辑  收藏  举报

this
在JavaScript中,this通常指向的是我们正在执行的函数本身,或者是指向该函数所属的对象(运行时)。当我们在页面中定义了函数 doSomething()的时候,它的owner是页面,或者是JavaScript中的window对象(或 global对象)。对于一个onclick属性,它为它所属的HTML元素所拥有,this应该指向该HTML元素。
2.1在几种常见场景中this的变化
函数示例
function doSomething ()
{
alert(this.navigator); //appCodeName
this.value = "I am from the Object constructor";
this.style.backgroundColor = "# 000000";
}
1. (A)作为普通函数直接调用时,this指向window对象.
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)”>作为参数传递可以指向element
3. (C)作为对象使用时this指向当前对象。形如:new doSomething();
4. (D)使用apply 或者call方法时,this指向所传递的对象。
形如:var obj={}; doSomething.apply(obj,new Array(”nothing”); //thisàobj

追加:如果希望事件调用时仍然把this指定为特定的对象,可以通过以下方法实现:

 

Function.prototype.bind = function(obj)
{
    var method = this;

    var temp = function()
    {
        return method.apply(obj, arguments);
    };

    return temp;
 }

function load()

{

     this.aa = "hello";

     this.show = function()

     {

        alert(this.aa);  

     };

}

var newclass = new load();

document.body.onload = newclass.show.bind(newclass);