JS USES the Array functions shift and pop to create an example of an argument that can be ignored

  • 2020-03-30 03:05:13
  • OfStack

Here, we can make use of the arguments object of the function, as well as the shift and pop in the Array to achieve flexible application.

Use shift
To implement a.bind() method, let the fn API look like this:


//The scope of fn is limited to object
//All arguments to the bind method except object are passed to fn
fn.bind(object, param1, param2, [, paramN]);

Let's look at an example. Of course, this example may be more important for the application of call and apply. However, what we want to talk about is the shift app:

//From the Prototype. Js [` bind `] (http://www.prototypejs.org/api/function/bind) method
Function.prototype.bind = function(){
  var fn = this,
      args = Array.prototype.slice.call(arguments),
      object = args.shift();
  return function(){
      return fn.apply(object,
          args.concat(Array.prototype.slice.call(arguments)));
      };
};

We can shift out arguments objects (array-like object, which needs to be converted to an actual array), like this method, which USES them primarily to separate out scoped objects, and then artfully pass the remaining array of arguments to fn, which calls the function we want to limit to the object scope.


Related articles: