Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
394 views
in Technique[技术] by (71.8m points)

关于js call apply的一些疑问

  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正常


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

call 和 apply 非常相似, 相同点:

  1. call 和 apply 都是对函数对象的调用
  2. call 和 apply 第一个参数都是指定 this

他们的不同点是, call 的后续参数是展开的, apply 的后续参数是一个包含了所有参数的参数列表

以下三种完全等价:


console.log(Math.max(1, 2, 3))

console.log(Math.max.call(null, 1, 2, 3))

console.log(Math.max.apply(null, [1, 2, 3]))

而你的代码中第一个

let a = [1, 2, 3, 4, 5, 6].shift.call([2, 4])

应该是没有理解的情况下的误用:

  1. 首先 Arrayshift 方法没有参数
  2. 上述代码实际上是执行了这个:
[2, 4].shift() // 返回 2

原因是你替换了 shift 这个函数执行目标的 this 对象, 所以实际上已经在另一个数组上执行了 shift() 方法


建议细读文档

Array.prototype.shift
Function.prototype.call
Function.prototype.apply


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...