JavaScript: The Right Parts - Chapter 8, function.apply ()

advertisements

For the following code, based on page 84 of "JavaScript: The Good Parts", can someone explain why [1] and [0] are used? I understand that they're supplying the arguments 1 and 0 to slice, respectively, but what's the point of that?

Function.prototype.bind = function (that) {
  var method = this;
  var slice = Array.prototype.slice;
  var args = slice.apply(arguments, [1]); // Why is [1] here?

  return function () {
    return method.apply(that, args.concat(slice.apply(arguments, [0]))); // Why is [0] here?
  };
};

var x = function () {
  return this.value;
}.bind({ value: 666 }); 

console.log(x()); // Returns 666.

I believe I understand the big picture - the function x has been designed to extract the value of the value property. We then bind an object that has a value property name/value pair and execute the x function. The x function reaches into the supplied object, as if it where a method of that object, and returns the value of the value property.

What I do not understand is how this is accomplished (I note Crockford's quasi-amusing use of 666). Thanks in advance.


The second argument for apply needs to be an array, if [2] were 2 instead, this would happen

Array.prototype.slice.apply(arguments, 2); Uncaught TypeError: Function.prototype.apply: Arguments list has wrong type

arguments is a baked in property which represents all of the arguments send to a function in an array like object. slicing this array will remove unwanted parts. In the case of bind, that is passed as an argument so slicing after 1 will remove that.

As a result

var args = slice.apply(arguments, [1]); // Why is [1] here?

Will take all of the extra arguments sent to bind, for example .bind({},1,2,3,4) will result in args being [1,2,3,4]

Next, a function is returned

return function () {
 return method.apply(that, args.concat(slice.apply(arguments, [0]))); // Why is [0] here?
};

that is going to be the new scope to use, method is the function that bind was originally called from, args.concat is going to take the previous array examined, and then add in all of the arguments which the method was called with, which is why [0] was used as opposed to [1] (where that was passed and was not being used as an argument for the method).