arrays - JavaScript: unsure how call and apply relate to the arguments object in this function -
in abstract way, totally understand what's going on. great way have unlimited number of arguments functions being passed calculate
object.
var calculate = function(){ var fn = array.prototype.pop.apply(arguments); return fn.apply(null, arguments); }, sum = function(x,y){ return x + y; }, diff = function(x,y){ return x - y; };
this appears crux of function. using apply
method here allow arguments
object have pop
method of array prototype
where unclear is...
the tut says going give function
object , assign fn
variable, remove function
object arguments
object, because of pop
method. (the pop
method removes last item of array, , assigns ever called pop method) in case fn
variable. end arguments
object, no longer has function object, has numeric values
var fn = array.prototype.pop.apply(arguments); return fn.apply(null, arguments);
recently, started realize perhaps misunderstanding seeing fn
variable that, , not function passed calculate
object.
thanks in advance helping me understand this!!
this syntax of apply:
function.apply(thisarg, [argsarray])
let's use calculate on sum:
calculate(10, 15, sum);
inside calculate:
in start - arguments = [10, 15, sum];
note arguments not array, array object - using array notation easier
var fn = array.prototype.pop.apply(arguments);
arguments not array, doesn't have pop method, take pop method array prototype , run on arguments - means use arguments 'this' prop of .pop()
. returns last parameter of arguments, supposed function (sum in case).
after pop - arguments = [10, 15];
now take arguments , use 2nd part of .apply(thisarg, [argsarray])
method - argsarray.
in fn.apply(null, arguments)
thisarg = null (doesn't matter function sum doesn't use this), , apply assigns arguments parameters in 'array' order - x (1st) = 10, y (2nd) = 15, , runs function.
Comments
Post a Comment