js apply()和call()用法

JavaScript中的每一个Function对象都有一个apply()方法和一个call()方法,它们的语法分别为:

1.apply()方法

function.apply(thisObj[, argArray])

2.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的功能是一样的,只是传入的参数列表形式不同

1.基本用法

{

function add(a, b) {

return a + b;

}

function sub(a, b) {

return a - b;

}

let a1 = add.apply(sub, [4, 2]);  //sub调用add的方法

let a2 = sub.apply(add, [4, 2]);

console.log(a1); //6

console.log(a2); //2

/*call的用法*/

let a3 = add.call(sub, 4, 2);

console.log(a3);

}

(2)实现继承

{

function Animal(name) {

this.name = name;

this.showName = function () {

console.log(this.name)

}

}

function Cat(name) {

Animal.apply(this, [name])

}

let cat = new Cat("猫咪");

cat.name = "猫咪";

console.log(cat.showName())



//call()用法

// Animal.apply(this, name)

}

 (3)多重继承

{

function Class10() {

this.showSub = function (a, b) {

console.log(a - b);

}

}

function Class11() {

this.showAdd = function (a, b) {

console.log(a + b);

}

}

function Class12() {

Class10.apply(this);

Class11.apply(this);

// Class10.call(this);

//Class11.call(this);

}

var c2 = new Class12();

c2.showSub(3, 1); //2

c2.showAdd(3, 1); //4

}

 4.apply的一些其他巧妙用法

 求最大值和最小值

{

let array = [1, 3, 2, 6, 4, 6, 34, 5, 32, 2, 6, 3];

console.log(Math.max.apply(null, array));

console.log(Math.min.apply(null, array));



// es6

console.log(Math.max(...array));

console.log(Math.min(...array));

}

 实现两个数组的合并

{

let array1 = [1, 3, 2, 6, 4], array2 = [6, 34, 5, 32, 2, 6, 3];

console.log(Array.prototype.push.apply(array1, array2));

console.log(array1)

// console.log(array1.push(...array2))

// console.log(array1)

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值