Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you reference Array.prototype.slice.call()?

I am writing a script in which I need to clone arrays in many different places. For this reason, I would like to do the following to emulate a cloning function:

var clone = [].slice.call;
var arr1 = [1,2,3,4,5,6,7,8,9,10];
var arr2 = clone(arr1, 0);

Unfortunately, the above code results in: TypeError: object is not a function. I realize there are many functions out there to do deep cloning and shallow copies but I just want to use the built in method. Interestingly enough, the following does work:

var clone = [].slice;
var arr1 = [1,2,3,4,5,6,7,8,9,10];
var arr2 = clone.call(arr1, 0);

Does anyone know why the first block doesn't work while the second does? Is there any way to reference a functions call and apply functions without throwing errors when calling the referenced function?

like image 438
Clarence Fredericks Avatar asked Jul 26 '11 19:07

Clarence Fredericks


1 Answers

I have to definitely agree with both Felix King and pimvdb. I think the only drawback to using the Function.protoytpe.bind() function is the fact that this is not a function that is available in all browsers (IE6 for example). An alternative would be to use a JavaScript library that provides the curry() function. Another alternative would be to define a function which gives you the ability to retrieve the call function for any other function. Here is a definition that I posted on my blog for such a function which I called getCall():

Function.prototype.getCall = function() {
  var realFn = this;
  return function(objThis) {
    return realFn.apply(objThis, Array.prototype.slice.call(arguments, 1));
  };
};

Now, with this definition, you could do the following to get a reference to the call function of the slice function:

var slice = [].slice.getCall();
like image 193
Chris West Avatar answered Oct 14 '22 18:10

Chris West