Saturday, July 4, 2015

Array.prototype.slice.call() madness!

This way to make slice shallow copies à la .slice against not an array but instead a regular object surfaces on page 25 of Kyle Simpson's "this & OBJECT PROTOTYPES" and he does not immediately explain it. Perhaps this is a teaser of something to come. I had to Google it and this example was found at StackOverflow:

var my_object = {
   '0': 'zero',
   '1': 'one',
   '2': 'two',
   '3': 'three',
   '4': 'four',
   length: 5
};
var sliced = Array.prototype.slice.call(my_object, 3);
console.log(sliced);

 
 

The object has to have a length bolted onto it and if the properties don't have numbers for names goofy badness occurs. This example will give us an array with two strings in it, the first being three and the later being four. Why would you ever want to use this horrible functionality? Earlier in his book, Kyle suggests he does not feel that developers should focus on the distinction between the "good parts" of JavaScript versus the "bad parts" of JavaScript and that really you need to understand all of it and not just the stuff you like. Perhaps his philosophy is manifesting in his Array.prototype.slice.call() example.

No comments:

Post a Comment