2

I am trying to write a static version of slice.

What is the difference between

Function.prototype.call.bind(Array.prototype.slice) 

and

Array.prototype.slice.call.

If I write:

var x = Array.prototype.slice.call; 
x([1,2,3]);

I get

TypeError: object is not a function.

Why is this?

1

2 Answers 2

1

The function Array.prototype.slice.call is the same exact function as Function.prototype.call. It does not know that Array.prototype.slice should be this unless you call it as a method, like so:

Array.prototype.slice.call(whatever);

or if you use one of a few other ways to tell it what this is. When you assign it to x, you lose the this information.

Function.prototype.call.bind(Array.prototype.slice) creates a function that does know that Array.prototype.slice is this. Even if you attach it to a new object and call it as a method of the new object:

x = {call: Function.prototype.call.bind(Array.prototype.slice)}
x.call([1, 2, 3])

It will behave as though it were called as Array.prototype.slice.call instead of x.call.

1
  • There is a section in Javascript Garden that explains this idea, that when you assign a method to a variable you lose the this context. I did not fully digest it, though, so I could not make the connection myself. Thanks.
    – asp
    Commented Jan 19, 2014 at 22:53
0

Here's your hint - this is true:

Array.prototype.slice.call == (function() {}).call

call is a member of Function.prototype - it expects the this argument to point to the function to call. You're passing it nothing, so this refers to the window object. This will work:

x = Array.prototype.slice.call.bind(Array.prototype.slice)

But from my first code snippet, Array.prototype.slice.call is just Function.prototype.call, so:

x = Function.prototype.call.bind(Array.prototype.slice)

In fact, Function.call == Function.prototype.call, so you can do

x = Function.call.bind(Array.prototype.slice)
1
  • He's not passing the array as this, he's passing nothing.
    – Bergi
    Commented Jan 19, 2014 at 22:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.