對javascript中call()方法的理解

來源:互聯網
上載者:User

標籤:time   code   函數   var   對象   改變   幾句話   瀏覽器   上下文   

call ( thisObj [, arg1 [, arg2 [,  [, argN] ] ] ])

call()方法:官方介紹是,調用一個對象的一個方法,以另一個對象替換當前對象。

     call()方法應用於Function對象,可以用來代替另一個對象調用一個方法,可將一個函數的物件內容從初始的上下文改變為thisObj指定的新對象。如果沒有提供thisObj參數,那麼Global對象被用作thisObj.

  直接理解這幾句話還是挺難理解的。先看一個例子:

function Class1(){        this.name = ‘fine‘;        this.showName = function(){            console.log(this.name);            console.log(this);        };        console.log(this);    }
  //執行個體化建構函式 var class1 = new Class1(); class1.showName();

在Chrome瀏覽器中測試的結果是:

可以看到兩個console.log(this)的值是一樣的,均指向建構函式;

然後再把上面的例子修飾一下:

  function Class1(){        this.name = ‘fine‘;        this.showName = function(){            console.log(this.name);            console.log(this);        };        console.log(this);    }    function Class2(){        this.name = ‘ok‘;    }    //建立相應的執行個體    var class1 = new Class1();    var class2 = new Class2();    class1.showName.call(class2);//call方法必須應用於函數對象上

在瀏覽器中測試如下:

第一個Class1對象是位於Class1建構函式中showName方法之外的console.log(this),在使用call方法後,即

  class1.showName.call(class2);

這個位於showName方法之外的this仍然指向的是Class1.

接下來的 ok 和 Class2對象是位於showName方法內部的,this的指向已經改變,指向了Class2建構函式。可見,call方法改變了它所應用的函數中的this指標的指向。

暫時對call方法的理解就是這樣了,以後有別的理解再補上,也可能有不對的地方歡迎補充~~

參考了Bparadise的部落格文章:http://www.cnblogs.com/wuyuetian/p/4999723.html

 

對javascript中call()方法的理解

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.