JavaScript實現繼承機制(2)——調用call()與apply()方法

來源:互聯網
上載者:User

前面介紹過JavaScript中通過對象冒充來實現繼承,這是最原始的方法。本文將介紹兩種很類似於對象冒充的繼承方式,即使用call()和apply()方法。

call() 方法

call() 方法是與經典的對象冒充方法最相似的方法。它的第一個參數用作 this 的對象。其他參數都直接傳遞給函數自身。例如:

function sayHello(sPrefix,sSuffix) {    alert(this.name + ”says“ + sPrefix + sSuffix);};var obj = new Object();obj.name = "Tom";sayHello.call(obj, "Hello ", "World.");

在這個例子中,函數 sayHello() 在對象外定義,即使它不屬於任何對象,也可以引用關鍵字 this。對象 obj 的 name屬性等於 blue。調用 call() 方法時,第一個參數是 obj,說明應該賦予 sayHello() 函數中的 this 關鍵字值是 obj。第二個和第三個參數是字串。它們與 sayHello() 函數中的參數 sPrefix 和 sSuffix 匹配,最後產生的訊息 "Tom says Hello World." 將被顯示出來。

要與繼承機制的對象冒充方法一起使用該方法,只需將前三行的賦值、調用和刪除代碼替換即可:

function ClassA(sColor) {    this.color = sColor;    this.sayColor = function () {        alert(this.color);    };}function ClassB(sColor, sName) {    //this.newMethod = ClassA;    //this.newMethod(color);    //delete this.newMethod;    ClassA.call(this, sColor);    this.name = sName;    this.sayName = function () {        alert(this.name);    };}

這裡,我們需要讓 ClassA 中的關鍵字 this 等於新建立的 ClassB 對象,因此 this 是第一個參數。第二個參數 sColor 對兩個類來說都是唯一的參數。

apply() 方法

apply() 方法有兩個參數,用作 this 的對象和要傳遞給函數的參數的數組。例如:

function sayColor(sPrefix,sSuffix) {    alert(sPrefix + this.color + sSuffix);};var obj = new Object();obj.color = "blue";sayColor.apply(obj, new Array("The color is ", "a very nice color indeed."));

這個例子與前面的例子相同,只是現在調用的是 apply() 方法。調用 apply() 方法時,第一個參數仍是 obj,說明應該賦予 sayColor() 函數中的 this 關鍵字值是 obj。第二個參數是由兩個字串構成的數組,與 sayColor() 函數中的參數 sPrefix 和 sSuffix 匹配,最後產生的訊息仍是 "The color is blue, a very nice color indeed.",將被顯示出來。

該方法也用於替換前三行的賦值、調用和刪除新方法的代碼:

function ClassB(sColor, sName) {    //this.newMethod = ClassA;    //this.newMethod(color);    //delete this.newMethod;    ClassA.apply(this, new Array(sColor));    this.name = sName;    this.sayName = function () {        alert(this.name);    };}

同樣的,第一個參數仍是 this,第二個參數是只有一個值 color 的數組。可以把 ClassB 的整個 arguments 對象作為第二個參數傳遞給 apply() 方法:

function ClassB(sColor, sName) {    //this.newMethod = ClassA;    //this.newMethod(color);    //delete this.newMethod;    ClassA.apply(this, arguments);    this.name = sName;    this.sayName = function () {        alert(this.name);    };}

當然,只有超類中的參數順序與子類中的參數順序完全一致時才可以傳遞參數對象。如果不是,就必須建立一個單獨的數組,按照正確的順序放置參數。此外,還可使用 call() 方法。

我們可以看到這兩個方法能夠很好的代替原始的對象冒充,使寫法上變得稍微簡單。但是這些方法的弊端是子類不能繼承父類在原型鏈上聲明的方法或屬性,針對這個問題下一篇文章將會介紹JavaScript中另一種實現繼承的方式—原型鏈繼承。

相關文章

聯繫我們

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