JS中call()和apply()

image.png

每個(gè)函數(shù)都包含兩個(gè)非繼承而來的方法:call()和apply();

在JavaScript中,call和apply作用是一樣的,都是為了改變某個(gè)函數(shù)運(yùn)行時(shí)的上下文(context)而存在的,換句話說,就是為了改變函數(shù)體內(nèi)部this的指向。

function fruits(){}
        
fruits.prototype = {
    color: "red",
    say: function(){
        console.log("My color is " + this.color);
    }
};

var apple = new fruits;
apple.say();                //My color is red

當(dāng)想另外一個(gè)對(duì)象想使用fruits中的say方法時(shí)不用重新寫,使用call和apply可以實(shí)現(xiàn)“劫持”別人的方法。

function fruits(){}
            
fruits.prototype = {
    color: "red",
    say: function(){
        console.log("My color is " + this.color);
    }
};

var another = {
    color: "yellow"
};

var apple = new fruits;
apple.say();                //My color is red
apple.say.call(another);    //My color is yellow
apple.say.apply(another);   //My color is yellow

區(qū)別:參數(shù)書寫方式不同

call(thisObj, arg1, arg2, arg3, arg4);

apply(thisObj, [args]);

thisObj:call和apply第一個(gè)參數(shù)是一樣的,該參數(shù)將替代Function類里面的this對(duì)象。
arg1,arg2....:是一個(gè)個(gè)的參數(shù),
args:一個(gè)數(shù)組或類數(shù)組,是一個(gè)參數(shù)列表。

用法

改變函數(shù)作用域

var name = "小白";
var obj = {
    name: "小紅"
};

function sayName() {
    return this.name;
}
console.log(sayName.call(this));   //小白
console.log(sayName.call(obj));    //小紅

實(shí)現(xiàn)繼承

//實(shí)現(xiàn)js繼承
//父類
function Person(name, height) {
    this.sayInfo = function() {
        return "姓名:" + name + ", 身高:" + height + ", 體重:" + this.weight;
    }
}
//子類
function Chinese(name, height, weight) {
    Person.call(this, name, height);
    this.weight = weight;
    
    this.nation = function() {
        console.log("我是中國(guó)人");
    }
}
//子類
function America(name, height, weight) {
    Person.apply(this, [name, height]);
    this.weight = weight;
}

let chiness = new Chinese("成龍", "178cm", "60kg");
console.log(chiness.sayInfo());    //姓名:成龍, 身高:178cm, 體重:60kg
let america = new America("jack", "180cm", "55kg");
console.log(america.sayInfo());    //姓名:jack, 身高:180cm, 體重:55kg
                         end   如有偏頗,下方評(píng)論區(qū)留言 
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容