Implement the bind function manually

  1. If the function returned by bind appears as a constructor with the new keyword, the bind’s this will be ‘ignored’. To implement such a rule, developers need to consider how to distinguish between the two invocation methods. Specifically, we do this instanceof checks in our bound function.
  2. Another detail: The function has the length attribute, which is used to indicate the number of parameters. In the following implementation, the number of parameters is obviously distorted. Therefore, the improved implementation requires the restoration of the Length attribute. The difficulty, however, is that the value of the function’s length attribute cannot be overridden.
// Implement a bind function
Function.prototype.bind = Function.prototype.bind || function(context){
  var me = this;
  var args = Array.prototype.slice.call(arguments.1);
  return function bound(){
    var innerArgs = Array.prototype.slice.call(arguments);
    var finalArgs = args.concat(innerArgs);
    returnme.apply(context,finalArgs); }}Copy the code