系列文章目录
提示:写完文章后,目录可以自动生成,如何生成可参考右边的帮助文档
在JS中使用apply
前言
提示:以下是本篇文章正文内容,下面案例可供参考
一、Function.prototype.apply()
根据MDN官网的说法,apply() 方法调用一个具有给定 this 值的函数,以及以一个数组(或一个类数组对象)的形式提供的参数。
二、apply的简单使用
1.用 apply 将数组各项添加到另一个数组
const array = ['a', 'b'];
const elements = [0, 1, 2];
array.push.apply(array, elements);
console.log(array); // ["a", "b", 0, 1, 2]
2.在对象B中使用A的方法,并使用apply改变this的指向,arguments就是传入的参数:
代码如下(示例):
/**
* node环境
*/
var obj = {
name: '张三',
func_A:function(age,score){
console.log(this.name+"的年龄是"+age,'成绩是:'+ score+ '分 ');
}
}
var obj1 = {
name: '李四',
func_B:function(){
console.log(this.name,arguments); //李四 [Arguments] { '0': 14, '1': 56 }
obj.func_A.apply(obj1,arguments)
}
}
obj1.func_B(14,56) //李四的年龄是14 成绩是:56分
3、可能会产生无限递归
var B = {
name:"张三",
funB:function()
{
console.log(this.name,arguments);
B.funB.apply(this,arguments)
}
};
B.funB("男生",20);
这段代码会无限递归是因为在 funB 函数中,每次都会调用 B.funB.apply(this,arguments),这里的 this 指向的是 B 对象本身,所以会一直调用自己的 funB 函数,导致无限递归。