调用一个不需要传递参数的函数变量
如果你看这条线https://github.com/hapijs/hapi-auth-basic/blob/master/lib/index.js#L14,你可以看到它调用internals.implementation
而不传入任何参数,但该方法有2个参数https://github.com/hapijs/hapi-auth-basic/blob/master/lib/index.js#L14。调用一个不需要传递参数的函数变量
如果方法internals.implementation
没有传入参数,它是如何工作的?
在第14行,internals.implementation
实际上未被调用。相反,对该函数的引用正在传递给plugins.auth.scheme()
,可能稍后将由auth
插件(其中实际参数将被传递)调用。
例如,这里有一个简化版本:
function sampleImplementation(message) {
alert(message);
}
function useImplementation(implementation, message) {
implementation.apply(this, [message]); // invoke the function with args
}
useImplementation(sampleImplementation, "hey there!"); // should alert "hey there!"
哦,好吧,这是有道理的。那么,如果你想添加另一个参数给函数呢?你会添加它作为方法签名中的最后一个参数,这样我就不会搞错前两个参数了吗? – Catfish 2014-11-14 15:12:09
@Catfish你需要在定义时在函数本身上定义一个形式参数,并且还要修改它在调用时提供第三个实参的位置。另一个选择是传递一个包装函数而不是'internals.implementation'本身:设置'otherArg =“...”;'然后定义'function(arg1,arg2){internals.implementation(arg1,arg2,otherArg) ; }'传递两个参数的包装函数,而不是'执行'本身。 (注意,如果消费函数明确检查回调是否为'implementation',这可能会破坏事情。) – apsillers 2014-11-14 15:27:55
这行代码是不是调用函数的。它传递一个对函数的引用,大概是稍后调用的参数。 – 2014-11-14 15:11:09