The first parameter problem of apply?

const args = [11, 12]
add.apply(null, args);
null
Apr.08,2022

pass null to the global object window


. Generally, parameters are entered only for the purpose of entering parameters. Generally, this usage is not to change this , but to change the method of passing parameters.
can be replaced by add (. [1 code 2]) .


The first parameter of

apply is the this value in the function. If this is not used in the add function, then this this parameter can be casually , but for simplicity, you generally pass in null . Of course, you can pass in 1 undefined quotation hello' , but you are accustomed to passing null , which means that the value of this is not used in the function:

'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

in non-strict mode, the first parameter passed to the apply method is undefined or null, then the this points to the global object. In
strict mode, this is the first parameter passed to the apply method.

Menu