【问题标题】:Function.prototype.bind.apply meaning not understood [duplicate]Function.prototype.bind.apply 含义不理解 [重复]
【发布时间】:2017-07-17 04:38:29
【问题描述】:

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

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

代码。为什么我们要调用apply for bind?是不是像打电话申请申请一样?

我在一些问题上读到它可以用来调用任意参数的函数,但这可以通过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))();
    }

【问题讨论】:

  • args 可能是一个数组。
  • 是的,申请数组并调用参数以便将ctor分配为this

标签: javascript angularjs


【解决方案1】:

跳过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. 'return new func();`

而上面的代码是injector用angular来获取service的实例的。

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

服务通过函数构造函数返回对象。这就是为什么您可以在服务中使用关键字“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))();
    }

【讨论】:

  • 当然,语法是可以理解的,但代码的目的是什么?它有什么作用?
  • @AndrewLi 我猜,我已经回答了任何问题。
  • 绑定有什么作用?
  • ok 我想问一下目的是什么?
  • @anurag bind 将返回一个带有预先限定的 `this' 的新函数
猜你喜欢
  • 2017-05-02
  • 2021-10-28
  • 2015-06-26
  • 2013-12-29
  • 1970-01-01
  • 1970-01-01
  • 2019-12-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多