js中apply和call方法有什么不同

匿名用户 分类:前端面试题

apply和call之间的唯一区别是如何在被调用的函数中传递实参。使用apply时,我们将实参作为数组传递,而使用apply时,我们将实参直接传递到实参列表中。

const obj1 = {
 result:0
};

const obj2 = {
 result:0
};

function reduceAdd(){
   let result = 0;
   for(let i = 0, len = arguments.length; i < len; i++){
     result += arguments[i];
   }
   this.result = result;
}

reduceAdd.apply(obj1, [1, 2, 3, 4, 5]); // returns 15
reduceAdd.call(obj2, 1, 2, 3, 4, 5); // returns 15

回复

我来回复
  • 暂无回复内容