apply/call是干什么用的
在JS中每一个function对象都有一个apply()和call()方法
/* apply()方法*/
function.apply(thisObj[, argArray])
/*call()方法*/
function.call(thisObj[, arg1[, arg2...]]);
定义
- apply:调用一个对象的一个方法,用另一个对象替换当前对象。例:B.apply(A, arguments);A对象应用B对象的方法;
- call:调用一个对象的一个方法,用另一个对象替换当前对象。例:B.call(A, args1, args2);A对象应用B对象的方法;
他们都是用来代替另一个对象调用一个方法,将一个函数的对象上下文从初始的上下文改变为由thisObj指定的新对象。
举例子
1.基本用法
function add(a,b){
return a+b
}
function sub(a,b){
return a-b
}
var a1= add.apply(sub,[4,2])
var a2= sub.apply(add,[4,2])
console.log(a1);//6
console.log(a2);//2
/*call的用法*/
var a3= add.call(sub, 4, 2)
2.实现继承
function Animal (name){
this.name= name;
this.showName= function(){
console.log(this.name)
}
}
function Cat(name){
Animal.apply(this.[name]);
}
var cat= new Cat('喵喵');
cat.showName();
// 喵喵
/*call的用法*/
Animal.call(this,name)
3.多重继承
function Class10(){
this.showSub= function(a, b){
console.log(a-b)
}
}
funciton Class11(){
this.showAdd= function(a, b){
console.log(a+b)
}
}
// 进行继承
function Class12(){
Class10.apply(this)
Class11.apply(this)
}
var c2= new Class12();
c2.showSub(3,1);//2
c2.showAdd(3,1);//4
实例举例
var arr = [4,1,3,7,5,8];
var max=Math.max.apply(null, arr)
console.log(max);//8
照着敲一遍,印象深刻
来源:https://www.cnblogs.com/lengyuehuahun/p/5643625.html