I know it is used to make arguments a real Array, but I don‘t understand what happens when using Array.prototype.slice.call(arguments);.
I know it is used to make arguments a real Array , but I
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
What happens under the hood is that when
.slice()is called normally,thisis an Array, and then it just iterates over that Array, and does its work.How is
thisin the.slice()function an Array? Because when you do:…the
objectautomatically becomes the value ofthisin themethod(). So with:…the
[1,2,3]Array is set as the value ofthisin.slice().But what if you could substitute something else as the
thisvalue? As long as whatever you substitute has a numeric.lengthproperty, and a bunch of properties that are numeric indices, it should work. This type of object is often called an array-like object.The
.call()and.apply()methods let you manually set the value ofthisin a function. So if we set the value ofthisin.slice()to an array-like object,.slice()will just assume it’s working with an Array, and will do its thing.Take this plain object as an example.
This is obviously not an Array, but if you can set it as the
thisvalue of.slice(), then it will just work, because it looks enough like an Array for.slice()to work properly.Example: http://jsfiddle.net/wSvkv/
As you can see in the console, the result is what we expect:
So this is what happens when you set an
argumentsobject as thethisvalue of.slice(). Becauseargumentshas a.lengthproperty and a bunch of numeric indices,.slice()just goes about its work as if it were working on a real Array.