let a = [1, 2, 3, 4, 5, 6].shift.call([2, 4])
let b = Math.max.apply([1, 2, 3])
let c = Math.max.apply(null,[1, 2, 3])
console.log(a);
console.log(b);
console.log(c);
为什么数组的shift方法不用传null就能使用,而math方法却要传null
a正常 b错误 c正常
let a = [1, 2, 3, 4, 5, 6].shift.call([2, 4])
let b = Math.max.apply([1, 2, 3])
let c = Math.max.apply(null,[1, 2, 3])
console.log(a);
console.log(b);
console.log(c);
为什么数组的shift方法不用传null就能使用,而math方法却要传null
a正常 b错误 c正常
首先 就没有 [.x.x.x.].shift.call()这种用法
.call 和 .apply 都是直接从原型对象获取方法,然后从传入两个参数(this(也就是执行的上下文环境), [...args])
所以你的 [1, 2, 3, 4, 5, 6].shift.call([2, 4])
等价于 Array.prototype.shift.call([2,4])
这个 [2,4] 不是args参数而是当this使用的
就等价于 [2,4].shift();
所以 同理
Math.max.apply([1, 2, 3])
这个 [1,2,3] 其实当作this传进去的
但其实Math作为js内置实例是不能被继承的,而且调用不需要this上下文,只需要入参就好了
所以最终等价于 Math.max(); 因为你没传递任何参数进去
10 回答11.1k 阅读
6 回答3k 阅读
5 回答4.8k 阅读✓ 已解决
4 回答3.1k 阅读✓ 已解决
2 回答2.6k 阅读✓ 已解决
3 回答5.1k 阅读✓ 已解决
3 回答1.8k 阅读✓ 已解决
call 和 apply 非常相似, 相同点:
他们的不同点是, call 的后续参数是展开的, apply 的后续参数是一个包含了所有参数的参数列表
以下三种完全等价:
而你的代码中第一个
应该是没有理解的情况下的误用:
Array
的shift
方法没有参数原因是你替换了 shift 这个函数执行目标的 this 对象, 所以实际上已经在另一个数组上执行了
shift()
方法建议细读文档
Array.prototype.shift
Function.prototype.call
Function.prototype.apply