Function.prototype.bind.apply意思不明白

时间:2017-02-26 16:18:28

标签: javascript angularjs

我正在查看角度的注入器代码,无法理解这一行

Function.prototype.bind.apply(ctor, args)

代码。为什么我们要求申请绑定?是不是要求申请申请?

我在一些问题上看到它可以用来调用任意参数的函数,但可以用arguments对象来完成,对吗?

有人可以清楚这个吗?

实际角度代码:

 function instantiate(Type, locals, serviceName) {
      // Check if Type is annotated and use just the given function at n-1 as parameter
      // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
      var ctor = (isArray(Type) ? Type[Type.length - 1] : Type);
      var args = injectionArgs(Type, locals, serviceName);
      // Empty object at position 0 is ignored for invocation with `new`, but required.
      args.unshift(null);
      return new (Function.prototype.bind.apply(ctor, args))();
    }

1 个答案:

答案 0 :(得分:5)

略过Function.prototype.bind.apply

首先,我们会看到apply

  

apply()方法调用具有给定this值的函数,并将参数作为array(或类似数组的对象)提供。

语法

fun.apply(thisArg, [argsArray])

所以使用上面的语法可以清楚地理解apply方法调用给定函数,第一个参数为this,第二个参数为Array

因此,请分解为步骤

  • Function.prototype.bind将返回一个具有预绑定this值的新函数。 (它在ES5中引入)。
  • apply方法使用给定的两个参数调用函数,如下所示。
    1. 第一个参数是this
    2. 第二个参数是Array / Array like object
  • 因此,在我们的示例中,我们将ctor作为thisargs作为对象的数组/数组传递给apply方法。

最终版本为return new (Function.prototype.bind.apply(ctor, args))();

  • 我们可以将上面的行分为两行,以便于阅读。
    1. var func = Function.prototype.bind.apply(ctor, args);
    2. '返回新的func();`

上面的代码由injector用于获取角度为service的实例。

根据定义,Angular服务将返回new'ed函数,因此上面的代码也是如此。

  

Services通过函数构造函数返回对象。这就是为什么你可以在服务中使用关键字'this'。

function instantiate(Type, locals, serviceName) {
      // Check if Type is annotated and use just the given function at n-1 as parameter
      // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
      var ctor = (isArray(Type) ? Type[Type.length - 1] : Type);
      var args = injectionArgs(Type, locals, serviceName);
      // Empty object at position 0 is ignored for invocation with `new`, but required.
      args.unshift(null);
      return new (Function.prototype.bind.apply(ctor, args))();
    }