Search code examples
javascriptprototypecallslice

Why does this piece of javascript gives different results?


function H() {

 }

H.prototype.K = function() {
      console.log(Array.prototype.slice.call(arguments, 1)); //gives [20, 30, 40]
      console.log(Array.prototype.slice(arguments, 1)); //gives []
   }

 H.prototype.K(10, 20, 30, 40)

Why calling slice directly gives empty array? If I can call function K directly, why can't I call slice directly?


Solution

  • Array.prototype.slice(arguments, 1) appear to be calling .slice() on Array.prototype

    See Array.prototype.slice() , Function.prototype.call()

    arr.slice([begin[, end]])

    Parameters

    begin

    Zero-based index at which to begin extraction. As a negative index, begin indicates an offset from the end of the sequence. slice(-2) extracts the last two elements in the sequence. If begin is omitted, slice begins from index 0.


    console.log(Array.prototype); // `[]` 
    console.log(Array.prototype.slice()); // `[]`
    console.log(Array.prototype.slice([10, 20, 30, 40], 1)); // `[]`
    console.log(Array.prototype.slice.call([10, 20, 30, 40] , 1)); // `[20, 30, 40]`
    console.log([].slice([10, 20, 30, 40], 1)); // `[]`
    console.log([].slice.call([10, 20, 30, 40] , 1)); // `[20, 30, 40]`