apply第一个参数问题?

const args = [11, 12]
add.apply(null, args);
第一个参数传递null的意义?
阅读 4.1k
4 个回答

apply的第一个参数是函数中的this值,如果add函数里面没有用到this,那么这个this参数就可以随便传入一个值,但是为了简便一般就传入null,当然你传入1,undefined,'hello'都可以,只不过都习惯传入null,代表函数里面并没有用到this的值:

'use strict';
function add (a, b) {
    console.log(this)
    return a + b
}
add.apply(null, [11, 12]) // null
add.apply(undefined, [11, 22]) // undefined
add.apply(1, [11, 22]) // 1

传null会指向全局对象window

一般只是为了填参数而填参数,这种用法一般不是要改变this,只是要改变传参方式。
可以用add(...[1,2])代替。

非严格模式下,传给apply方法的第一个参数是undefined或null,那么this就指向全局对象。
严格模式下,this就是传给apply方法的第一个参数。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题