0

I'm trying out some basic JS functionality:

function addUser(name, age, fun) {
    fun.apply(null, arguments); }

addUser("Peter",25, function(name) { console.log(name+"...from Function");});

but I just don't seem to understand why the first argument in fun.apply(null, arguments); needs to be null, and why I cannot simply do fun.apply(arguments); ?

R. Kohlisch
  • 2,823
  • 6
  • 29
  • 59
  • Because that's not the [function signature](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply). You might as well ask _"Why cannot I simply do `addUser(25)`?"_ – Phil Feb 06 '19 at 12:31

1 Answers1

1

The first argument of apply is the this object. You don't have to pass null, you could pass this or any other object as well, but you can't just pass arguments by itself because then arguments will become your this object in the function and name won't get a value.

Note that, for this example, you could just call fun(name) instead of fun.apply(null, arguments).

jvdmr
  • 685
  • 5
  • 12