2014-11-14 103 views
0

如果你看這條線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沒有傳入參數,它是如何工作的?

+0

這行代碼是不是調用函數的。它傳遞一個對函數的引用,大概是稍後調用的參數。 – 2014-11-14 15:11:09

回答

2

在第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!"

+0

哦,好吧,這是有道理的。那麼,如果你想添加另一個參數給函數呢?你會添加它作爲方法簽名中的最後一個參數,這樣我就不會搞錯前兩個參數了嗎? – Catfish 2014-11-14 15:12:09

+1

@Catfish你需要在定義時在函數本身上定義一個形式參數,並且還要修改它在調用時提供第三個實參的位置。另一個選擇是傳遞一個包裝函數而不是'internals.implementation'本身:設置'otherArg =「...」;'然後定義'function(arg1,arg2){internals.implementation(arg1,arg2,otherArg) ; }'傳遞兩個參數的包裝函數,而不是'執行'本身。 (注意,如果消費函數明確檢查回調是否爲'implementation',這可能會破壞事情。) – apsillers 2014-11-14 15:27:55

相關問題