I am confused by this code:
Function.prototype.apply.call(Math.floor, undefined, [1.75]); // 1
I read this post javascript apply and call methods and chain together and I understand the meaning of chaining apply and call methods together.
However, I am still confused about the syntax. The correct syntax for call is function.call(thisArg, arg1, arg2, ...)
. But in this case, why could the call method take these three parameters ( target
, thisArgument
, argumentsList
), which is the same as Reflect.apply(target, thisArgument, argumentsList)
?
Actually, call method can take all comma separated arguments and pass it to the called method. While as you see here (target, thisArgument, argumentsList)
Second two arguments work as arguments for apply method and we know that apply method gonna need an array of argument, we have sent third parameter as an array.
So here the execution can be simplified to :
Math.floor.apply(undefined, [1.75]);
Or simply Math.floor(1.75) // Obv with undefined as reference of this
Function.prototype.apply.call(Math.max, undefined, [1,75]); // 1
code above change thisArgu in Function.prototype.apply to Math.max
let's talk about change thisArgu in Function.prototype.apply to Math.max
noramlly, this in Function.prototype.apply should be Function.prototype
so change thisArgu in Function.prototype.apply to Math.max means:
change Function.prototype to Math.max if met 'this' when executing in Function.prototype.apply()
so code above can be understood like this when execute and meet 'this' :
Math.max.apply(undefined,[1,75])
now you understand?
if we go on ,you will find
Math.max.apply(undefined,[1,75])
can be understood like:
Window.max(1,75)//error;
so , i guess 'this' word doesn't exist in Math.max function content,so it gets no error;
The syntax for call()
is:
someFunctionOrMethod.call(...)
So, this code is calling the apply
method of the Function
type.
// Call the "apply()" method
Function.prototype.apply.call()
// With the following arguments passed to "apply"
(Math.floor, undefined, [1.75])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.