一、定义
apply()方法
接收两个参数,一个是函数运行的作用域(this),另一个是参数数组。
语法:apply([thisObj [,argArray] ]);调用一个对象的一个方法,另一个对象替换当前对象。
说明:如果argArray不是一个有效数组或不是arguments对象,那么将导致一个TypeError,如果没有提供argArray和thisObj任何一个参数,那么Global对象将用作thisObj。
call()方法
第一个参数和apply()方法的一样,但是传递给函数的参数必须列举出来。
语法:call([thisObject[,arg1 [,arg2 [,...,argn]]]]);应用某一对象的一个方法,用另一个对象替换当前对象。
说明: call方法可以用来代替另一个对象调用一个方法,call方法可以将一个函数的对象上下文从初始的上下文改变为thisObj指定的新对象,如果没有提供thisObj参数,那么Global对象被用于thisObj。
二、功能
apply与call功能相同,改变函数作用域的上下文-this
// 例1
// ================================
var nameColor='red',
cat={nameColor:'yellow'},
dog={nameColor:'blue'};
var changColor=function(){
console.log(this.nameColor);
}
changColor.call(null); //print:red
changColor.call(cat); //print:yellow
changColor.call(dog); //print:blue //一种写法
changColor.apply(dog); //print:blue //另一种写法
call()改变了函数changColor的this指向
// 例2
// ================================
var Dog ={
words:'汪汪',
say:function(_say){
console.log(_say+":"+this.words);
}
}
Dog.say("speak"); // speak:汪汪
var Cat ={
words:'喵喵',
say:function(_say){
console.log(_say+':'+this.words);
}
}
Dog.say.call(Cat,'speak'); // speak:喵喵 //一种写法
Dog.say.apply(Cat,['speak']); // speak:喵喵 //另一种写法
Dog的this指向变成了Cat
//例3 类的继承
// ================================
function Animal(name){
this.name = name;
this.showName = function(){
console.log(this.name);
}
}
function Cat(name){
Animal.call(this, name);
}
var cat = new Cat("Black Cat");
cat.showName(); //Black Cat
//例4 内置函数的扩充
//相当于contact方法
// ================================
var arr1=new Array("1","2","3");
var arr2=new Array("4","5","6");
Array.prototype.push.apply(arr1,arr2);
console.log(arr1);//["1", "2", "3", "4", "5", "6"]
//例5 求数组中的大小
// ================================
(function(){
var maxNum = Math.max.apply(null,arguments);
console.log(maxNum);//56
})(34,2,56);
//例5 求数组中的大小
// ================================
(function(){
var maxNum = Math.max.apply(null,arguments);
console.log(maxNum);//56
})(34,2,56);
以上就是apply与call的用法总结的全部内容,欢迎大家积极留言参加讨论
参考博客:
https://www.cnblogs.com/faithZZZ/p/6999327.html
https://blog.csdn.net/ganyingxie123456/article/details/70855586