+ 3
Javascript Spread in function calls
Could someone explain why do we need "null" in this case? And how to use apply for a function? Thank you. function myFunction(w,x,y,z) { console.log(w+x+y+z); } var args = [1,2,3]; myFunction.apply(null, args.concat(4));
2 Antworten
+ 2
apply() method takes two arguments. First an object, in this case myFunction will be called as that objects method, and second argument is an array. Here you just want to call a function independently using apply. So you have to specify null, so that it does not throw an error.
Since you don't have a this keyword in myFunction you can use any object instead of null as a first argument
0
in es6 we can rather use the spread operator to apply an array as arguments of a function:
myFunction(...args.concat(4));
or even:
myFunction(...args,4);
.apply() method should be reserved for very specific cases...