欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

基于JavaScript實現(xiàn)繼承機制之調(diào)用call()與apply()的方法詳解

 更新時間:2013年05月07日 18:06:27   作者:  
本文將介紹兩種很類似于對象冒充的繼承方式,即使用call()和apply()方法

call() 方法

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

復(fù)制代碼 代碼如下:

function sayHello(sPrefix,sSuffix) {
    alert(this.name + ”says“ + sPrefix + sSuffix);
};

var obj = new Object();
obj.name = "Tom";

sayHello.call(obj, "Hello ", "World.");


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

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

復(fù)制代碼 代碼如下:

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 中的關(guān)鍵字 this 等于新創(chuàng)建的 ClassB 對象,因此 this 是第一個參數(shù)。第二個參數(shù) sColor 對兩個類來說都是唯一的參數(shù)。

apply() 方法

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

復(fù)制代碼 代碼如下:

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


這個例子與前面的例子相同,只是現(xiàn)在調(diào)用的是 apply() 方法。調(diào)用 apply() 方法時,第一個參數(shù)仍是 obj,說明應(yīng)該賦予 sayColor() 函數(shù)中的 this 關(guān)鍵字值是 obj。第二個參數(shù)是由兩個字符串構(gòu)成的數(shù)組,與 sayColor() 函數(shù)中的參數(shù) sPrefix 和 sSuffix 匹配,最后生成的消息仍是 "The color is blue, a very nice color indeed.",將被顯示出來。

該方法也用于替換前三行的賦值、調(diào)用和刪除新方法的代碼:

復(fù)制代碼 代碼如下:

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


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

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


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

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

相關(guān)文章

最新評論