0
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?

amrka
  • 49
  • 1
  • 6
  • See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice – guest271314 Aug 22 '15 at 00:41
  • Given your call to `H.prototype.K(...)`, it seems you're not understanding some of the basics of how to use prototypal inheritance. That should very rarely be done. –  Aug 22 '15 at 00:51
  • 1
    [This answer](http://stackoverflow.com/questions/7056925/how-does-array-prototype-slice-call-work/7057090#7057090) may help give you a better understanding of why this is done. –  Aug 22 '15 at 01:01
  • `Array.prototype.slice(arguments, 1)` is equivalent to `Array.prototype.slice.call(Array.prototype, arguments, 1)`. Note that `call` always accepts a context as the first parameter. That should make it easier to track down the behavior.. – user2864740 Aug 22 '15 at 01:09
  • Because `Array.prototype` is an empty array. – Oriol Aug 22 '15 at 01:20

2 Answers2

2

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]`
guest271314
  • 1
  • 15
  • 104
  • 177
1

When you call the function directly, it gets a different context. When called as a method the context is the arguments array, but when you call it directly the context will be the Array.prototype object.

The second call won't try to get items from the arguments array, it will try to get items from the Array.prototype array (which acts as an empty array), using arguments as first index and 1 as length.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • The "context" will be `Array.prototype`, which is an Array (or looks enough like one). –  Aug 22 '15 at 00:51
  • Well, I saved arguments to args locally and executed slice on args, still got empty array. – amrka Aug 22 '15 at 00:51
  • @HarshSavla: How did you save the arguments to args? If you just assigned arguments to a variable then you just have another reference to the same object. – Guffa Aug 22 '15 at 00:59