
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ū)留言