介绍
JavaScript中的每一个Function对象都有一个apply()方法和一个call()方法
语法:
/*apply()方法*/
function.apply(thisObj[, argArray])
/*call()方法*/
function.call(thisObj[, arg1[, arg2[, [,...argN]]]]);
定义
apply
:调用一个对象的一个方法,用另一个对象替换当前对象。例如:B.apply(A, arguments)
;即A对象应用B对象的方法。
call
:调用一个对象的一个方法,用另一个对象替换当前对象。例如:B.call(A, args1,args2)
;即A对象调用B对象的方法。
相同之处
都“可以用来代替另一个对象调用一个方法,将一个函数的对象上下文从初始的上下文改变为由thisObj指定的新对象”。
不同之处
apply
:最多只能有两个参数——新this
对象和一个数组argArray
。如果给该方法传递多个参数,则把参数都写进这个数组里面,当然,即使只有一个参数,也要写进数组里。如果argArray
不是一个有效的数组或arguments
对象,那么将导致一个TypeError
。如果没有提供argArray
和thisObj
任何一个参数,那么Global
对象将被用作thisObj
,并且无法被传递任何参数。
call
:它可以接受多个参数,第一个参数与apply
一样,后面则是一串参数列表。这个方法主要用在js
对象各方法相互调用的时候,使当前this
实例指针保持一致,或者在特殊情况下需要改变this
指针。如果没有提供thisObj
参数,那么 Global
对象被用作thisObj
。
apply和call的功能是一样的,只是传入的参数列表形式不同
用途
基础(一)
function add(a, b) {
return a + b;
}
function sub(a, b) {
return a - b;
}
var a1 = add.apply(sub, [4, 2]); //sub调用add的方法
var a2 = sub.apply(add, [4, 2]);
console.log(a1); //6
console.log(a2); //2
/*call的用法*/
var a3 = add.call(sub, 4, 2);
var a4 = sub.call(add, 4, 2);
console.log(a3); //6
console.log(a4); //2
基础(二)
var mathMethods = function () {
this.methods = {
'add': function (a, b) {
console.log(a + b)
}
}
}
mathMethods.prototype.do = function () {
this.action['add']()
this.action['add'].call(this, 1, 2)
}
mathMethods.prototype.action = {
'add': function (a, b) {
console.log(this)
}
}
var math1 = new mathMethods()
math1.do()
//{ add: [Function: add] }
//math { methods: { add: [Function: add] } }
继承(一)
function Animals(name) {
this.name = name;
this.showName = function () {
console.log(this.name);
}
}
function Cat(name) {
Animals.apply(this, [name]);
// Animal.call(this, name);
}
var cats= new Cat("咕咕");
cats.showName();
//咕咕
继承(二)
function bird() {
this.fly = function (name) {
console.log(name + '会飞');
}
}
function cat() {
this.run = function (name) {
console.log(name + '会跑');
}
}
function animal() {
bird.apply(this);
cat.apply(this);
//bird.call(this);
//cat.call(this);
}
var animals = new animal();
animals.fly('麻雀'); //麻雀会飞
animals.run('小猫'); //小猫会跑
其他
实现查找数组最大最小值
Math.max
不支持Math.max([param1,param2])
也就是数组,但是它支持Math.max(param1,param2...)
,所以可以根据apply
的特点来解决 var max=Math.max.apply(null,array)
,这样就轻易的可以得到一个数组中的最大项(apply
会将一个数组转换为一个参数接一个参
const array = [1,2,3,4,5,6,7,8,9]
var max = Math.max.apply(null,array);
console.log(max)//9
var min = Math.min.apply(null,array);
console.log(min)//1