In JavaScript, the wording Array.prototype.slice.call (ARR, 2) is intended to be What?

  javascript

After reading a lot of JavaScript source code, I found many similar writing styles.

Array.prototype.slice.call(arr, 2)

What is more puzzling is that sincearrIs an array, why not write it like this directly

arr.slice(2)

Why does the instance object itself already have this method, and why does it not call directly and use this method instead? Is there any special purpose?

There is an array-like object in javascript inside, which is very similar to Array. For example, it has methods such as push, slice, etc. and has the length attribute. Moreover, you can easily create such an object:

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

Convert to an array object:

console.log(Array.prototype.slice.call(foo,0));
    //["hello", "world"]
    console.log(foo.slice())
    //["hello", "world"]

This is because this array-like object has this slice method. What if it doesn’t? Can’t use directly, to use the prototype method calls. As follows:

console.log(Array.prototype.splice.call(foo,0));
    //["hello", "world"]
    console.log(foo.splice())
    //TypeError: Object #<Object> has no method 'splice'

The commonly used arguments objects, document.links, document.forms, etc. are all very like Arrays, which can be converted into array operations by using Array.prototype.slice.call