What is the purpose of Array.prototype.slice.call (arr, 2) in JavaScript?

Source: Internet
Author: User

Read a lot of JavaScript source code, found a lot of similar wording

2)

It is puzzling that since arr is an array, why not write it directly?

Arr.slice (2)

Why does the instance object itself already have this method, why not call it directly, and use such a notation? Do you have any special intentions?

The main reason is to prevent some objects from having slice methods.

As an example:

In JavaScript, there is a Array-like object, which is like an array, such as having push,slice and so on, with the length property, and you can easily create an object like this:

var foo = {0:' Hello ',1:' world ', Length:2,slice:Array.prototype.slice}    

into an Array object:

Console. log (Array.  Prototype.slice.call (foo,0));    //["World"] console.  Log (Foo.slice ())//["World"]      

This is because this array-like object has this slice method, if not? Can not be used directly, to use the method of the prototype call. As follows:

Console. log (Array.  Prototype. Splice.call (foo,0));    //["World"] console.  Log (foo.  #<object> has no method ' splice '       

Commonly used arguments objects, document.links, document.forms, etc. are very similar to arrays (array), and you can use Array.prototype.slice.call to convert them into a group operation.

Again, consider this example: http://segmentfault.com/q/1010000000774633

What is the purpose of Array.prototype.slice.call (arr, 2) in JavaScript?

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.