this上下文,以及通過call 、apply 實現繼承

來源:互聯網
上載者:User

標籤:

上下文:this關鍵字通常指向當前函數的擁有者,把擁有者叫做執行內容。

this代表函數運行時自動產生的內部對象,只能在函數內部使用。

建構函式中的this 指 建構函式的執行個體對象。javascript存在定義時上下文和運行時上下文。

函數的 call 和 apply 方法 可以改變上下文執行對象。可以在自訂上下文中執行函數,call 函數需要參數列表,apply 需要一個數組參數。
調用對象的一個方法,以另一個對象替換當前對象,更改對象this指向的內容。以某個方法當做指定的某個對象的方法被執行。

var pet = {        words:‘…………‘,        speak:function(say){                console.log(say + ‘ ‘ + this.words)        }}pet.speak(‘Speak‘);var dog = {        words:"Wang",}pet.speak.call(dog,‘Speak‘)               // 輸出: Speak Wang

  

pet.speak.call(dog,‘Speak‘)
調用的方法是: pet.speak ,理論上說 this 指向pet對象, 但是通過call 改變了執行內容,把 this指標 指向了 dog 。使 dog對象 有了pet的speak方法 。第二個 ‘Speak’ 是前面的方法 pet.speak 的參數。

通過call或者apply 賦給第一個對象參數 dog 一種能力,即該對象可以調用 前面的方法 的能力。
通過call或者apply 方式,所指定的對象 dog ,這個對象是調用某個方法時,用這個對象作為該方法的上下文。

上面的方法是函數使用的時候才改變 this 對象,以下的程式是在函數定義的時候改變this上下文。

利用call 或者apply 改變 this  內容相關的特性 可以實現繼承。

function Pet(name,words){        this.name = name;
     this.words = words; this.speak = function(){ console.log(this.name + " say: " + this.words); }}
var pet = new Pet(‘Cat‘,‘MIAO‘);
pet.speak(); //輸出: Cat say: MIAO
function Dog(words){        Pet.call(this, words);        //把Pet 裡面的this 指向當前的 this對象,即 Dog 對象,使 Dog 擁有Pet 的方法。        //Pet.apply(this,arguments)}var dog = new Dog(‘Wang‘);            // call 實現了繼承。具有 Pet 的方法。dog.speak()                           // 輸出: Wang say: undefined

  

this上下文,以及通過call 、apply 實現繼承

聯繫我們

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