amrka
amrka

Reputation: 49

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?

Upvotes: 0

Views: 49

Answers (2)

guest271314
guest271314

Reputation: 1

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]`

Upvotes: 2

Guffa
Guffa

Reputation: 700680

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.

Upvotes: 1

Related Questions