javascript this的用法

來源:互聯網
上載者:User

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);

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.