0

In the book Oreilly.JavaScript.The.Good.Parts, there is a piece of code like this:

Function.method('curry', function () { 
    var slice = Array.prototype.slice, 
        args = slice.apply(arguments),
        that = this; 
    return function () {
         return that.apply(null, args.concat(slice.apply(arguments)));
     };
});

I wonder why not directly Array.prototype.slice instead of private variables, thanks.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
William
  • 171
  • 2
  • 5

3 Answers3

1

I think it's a nice to have, not a must be, i.e. either way would work.

It's slightly easier to read with the alias (because you have less code to parse).

If the curried method is called very often, then the alias will increase the performance since JavaScript won't have to go through the complex rules to dereference Array and then prototype.

Lastly, someone might overwrite Array.prototype.slice later (unlikely) or the author might have overwritten it for this function call (also unlikely). So the code makes sure that when you call it later, it behaves as if you had executed it right away.

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
0

It would work without defining slice, but there are two calls to Array.prototype.slice in this function, so it's good to define a 'shortcut', in order to make it look better (shorter code, less redundancy).

piokuc
  • 25,594
  • 11
  • 72
  • 102
0

From a performance perspective, slice is used twice in the code that follows. Using a shortcut will reduce both the length of the code to type, and the lookup process.

If you have slice in a local variable, there is single lookup needed when you access it:

  • getVar "slice"

In contrast, using Array.prototype.slice typically translate to several "instructions":

  • getVar "Array"
  • getMember "prototype"
  • getMember "slice"

From a minification perspective, tools like google compiler will also reduce the size code even further by renaming local variables (in this case slice) to a single letter variable. That can not happen for global vars accessed outside scope (In that case Array.prototype.slice).

From a functional perspective, Array.prototype.slice is resolved dynamically, so it can change later. Assigning a local reference to the function object pointed to by Array.prototype.slice at that point in time guarantees that no other code can change the function reference that you now hold yourself.

Timothée Groleau
  • 1,940
  • 13
  • 16