0
点赞
收藏
分享

微信扫一扫

apply方法

素的盐 2022-10-24 阅读 214

<script>
//先演示apply函数使用
function add(a, b) {
return a + b + this.c;
}
let obj = {
c: 520
}
// add.apply(obj,[10,20]);
console.log(add.apply(obj, [10, 20])); //550


//封装apply函数
//原理:和call方法类似,但是apply方法的参数接收的是数组,所以接收参数的时候不用展开数组,调用Fn函数时再展开数组进行传参
function apply(Fn, obj, args) {
obj.temp = Fn;
console.log(...args);
let res = obj.temp(...args);
delete obj.temp;
return res;
}

function count(a, b) {
return a + b + this.c;
}
let num = {
c: 1314
}
console.log(apply(count, num, [10, 30])); //1354
</script>

举报

相关推荐

0 条评论