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

Javascript中的call()方法介紹

 更新時間:2015年03月15日 10:25:09   投稿:junjie  
這篇文章主要介紹了Javascript中的call()方法介紹,本文講解了Call() 語法、Call() 參數(shù)、Javascript中的call()方法、Call()方法的實例等內(nèi)容,需要的朋友可以參考下

在Mozilla的官網(wǎng)中對于call()的介紹是:

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

call() 方法在使用一個指定的this值和若干個指定的參數(shù)值的前提下調(diào)用某個函數(shù)或方法.

Call() 語法
復(fù)制代碼 代碼如下:

fun.call(thisArg[, arg1[, arg2[, ...]]])

Call() 參數(shù)

thisArg

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

在fun函數(shù)運行時指定的this值。需要注意的是,指定的this值并不一定是該函數(shù)執(zhí)行時真正的this值,如果這個函數(shù)處于非嚴格模式下,則指定為null和undefined的this值會自動指向全局對象(瀏覽器中就是window對象),同時值為原始值(數(shù)字,字符串,布爾值)的this會指向該原始值的自動包裝對象。

arg1, arg2, ...
復(fù)制代碼 代碼如下:

指定的參數(shù)列表。

Javascript中的call()方法

先不關(guān)注上面那些復(fù)雜的解釋,一步步地開始這個過程。

Call()方法的實例

于是寫了另外一個Hello,World:

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

function print(p1, p2) {
    console.log( p1 + ' ' + p2);
}
print("Hello", "World");
print.call(undefined, "Hello", "World");

兩種方式有同樣的輸出結(jié)果,然而,相比之下call方法還傳進了一個undefined。

接著,我們再來看另外一個例子。

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

var obj=function(){};
function print(p1, p2) {
    console.log( p1 + ' ' + p2);
}

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

只是在這里,我們傳進去的還是一個undefined,因為上一個例子中的undefined是因為需要傳進一個參數(shù)。這里并沒有真正體現(xiàn)call的用法,看看一個更好的例子。

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

function print(name) {
    console.log( this.p1 + ' ' + this.p2);
}

var h={p1:"hello", p2:"world", print:print};
h.print("fd");

var h2={p1:"hello", p2:"world"};
print.call(h2, "nothing");

call就用就是借用別人的方法、對象來調(diào)用,就像調(diào)用自己的一樣。在h.print,當(dāng)將函數(shù)作為方法調(diào)用時,this將指向相關(guān)的對象。只是在這個例子中我們沒有看明白,到底是h2調(diào)了print,還是print調(diào)用了h2。于是引用了Mozilla的例子

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

function Product(name, price) {
    this.name = name;
    this.price = price;

    if (price < 0)
        throw RangeError('Cannot create product "' + name + '" with a negative price');
    return this;
}

function Food(name, price) {
    Product.call(this, name, price);
    this.category = 'food';
}
Food.prototype = new Product();

var cheese = new Food('feta', 5);
console.log(cheese);


在這里我們可以真正地看明白,到底是哪個對象調(diào)用了哪個方法。例子中,使用Food構(gòu)造函數(shù)創(chuàng)建的對象實例都會擁有在Product構(gòu)造函數(shù)中添加的 name 屬性和 price 屬性,但 category 屬性是在各自的構(gòu)造函數(shù)中定義的。

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

function print(name) {
    console.log( this.p1 + ' ' + this.p2);
}

var h2= function(no){
    this.p1 = "hello";
    this.p2 = "world";
    print.call(this, "nothing");
};
h2();

這里的h2作為一個接收者來調(diào)用函數(shù)print。正如在Food例子中,在一個子構(gòu)造函數(shù)中,你可以通過調(diào)用父構(gòu)造函數(shù)的 call 方法來實現(xiàn)繼承。

至于Call方法優(yōu)點,在《Effective JavaScript》中有介紹。

1.使用call方法自定義接收者來調(diào)用函數(shù)。
2.使用call方法可以調(diào)用在給定的對象中不存在的方法。
3.使用call方法可以定義高階函數(shù)允許使用者給回調(diào)函數(shù)指定接收者。

相關(guān)文章

最新評論