亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Javascript中的call()方法介紹

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

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

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

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

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

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

Call() 參數(shù)

thisArg

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

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

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

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

Javascript中的call()方法

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

Call()方法的實(shí)例

于是寫了另外一個(gè)Hello,World:

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

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

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

接著,我們?cè)賮砜戳硗庖粋€(gè)例子。

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

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

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

只是在這里,我們傳進(jìn)去的還是一個(gè)undefined,因?yàn)樯弦粋€(gè)例子中的undefined是因?yàn)樾枰獋鬟M(jìn)一個(gè)參數(shù)。這里并沒有真正體現(xiàn)call的用法,看看一個(gè)更好的例子。

復(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就用就是借用別人的方法、對(duì)象來調(diào)用,就像調(diào)用自己的一樣。在h.print,當(dāng)將函數(shù)作為方法調(diào)用時(shí),this將指向相關(guān)的對(duì)象。只是在這個(gè)例子中我們沒有看明白,到底是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);


在這里我們可以真正地看明白,到底是哪個(gè)對(duì)象調(diào)用了哪個(gè)方法。例子中,使用Food構(gòu)造函數(shù)創(chuàng)建的對(duì)象實(shí)例都會(huì)擁有在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作為一個(gè)接收者來調(diào)用函數(shù)print。正如在Food例子中,在一個(gè)子構(gòu)造函數(shù)中,你可以通過調(diào)用父構(gòu)造函數(shù)的 call 方法來實(shí)現(xiàn)繼承。

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

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

相關(guān)文章

最新評(píng)論