我正在查看角度的注入器代码,无法理解这一行
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))();
}
答案 0 :(得分:5)
略过Function.prototype.bind.apply
首先,我们会看到apply
。
apply()方法调用具有给定
this
值的函数,并将参数作为array
(或类似数组的对象)提供。
fun.apply(thisArg, [argsArray])
所以使用上面的语法可以清楚地理解apply
方法调用给定函数,第一个参数为this
,第二个参数为Array
因此,请分解为步骤
Function.prototype.bind
将返回一个具有预绑定this
值的新函数。 (它在ES5中引入)。apply
方法使用给定的两个参数调用函数,如下所示。
this
ctor
作为this
和args
作为对象的数组/数组传递给apply
方法。 最终版本为return new (Function.prototype.bind.apply(ctor, args))();
var func = Function.prototype.bind.apply(ctor, args)
; 上面的代码由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))();
}