I am calling a method using apply and I do not know how many arguments I will be passing:
At the moment my code looks like this:
selectFolder: function(e){
e.preventDefault();
this.addSelectedClass.apply(this, Array.prototype.slice.call(arguments));
},
The only reason I am using Array.prototype.slice is because it is in most examples.
Why would I not just pass arguments like this:
this.addSelectedClass.apply(this, arguments);
argumentswithapply()are fineWhen calling
applyon a function it’s ok to just use originalarguments. SO in your example you can easily replace the line with this one:argumentswithcall()are not fineBut if you’d be calling
callthen you should convertargumentsto an actual array (which is done by aslice()call) if you’d want to pass your function an array of arbitrary objects/values. That’s whycall()is usually used when you know exactly the number of arguments you’d want to pass and pass them individually.argumentsare not an actual array object. They seem to be (havelengthproperty for instance), but they’re not.Arguments on Mozilla Deveveloper Network
A bit of explanation to make it completely clear
Documentation related to
apply()andcall()looks like this:We may execute the same function using any of these.
When using
apply()we can pass all arguments at once.slice()is usually used to omit a particular argument from the call or to convertargumentsto actual array.When using
call()we pass individual arguments and as many as we need to. If we’d provide arguments converted to an array, our called function would get one parameter of type array with all arguments supplied in that particular array.I hope this clears thing up even more.