2017-02-23 57 views
-1

如何在函數上應用掛鉤。我想要在掛鉤函數前後應用,以便每當調用該函數時,這些掛鉤都會觸發。我已經看到了中間件express.js的概念但這隻適用於不適用於某個功能的路由,因爲它適用於路由處理。我需要一個類似於我的函數的鉤子,所以無論何時我的函數在鉤子觸發前後在服務器端調用。掛鉤在node.js中的函數

function main(){ console.log("When ever this function is called as myfun()"); } 

function after(){ 
    console.log("called afer when ever manin is called"); 
} 
+1

你能舉一個例子。爲什麼不簡單地包裝功能? –

+0

@DavinTryon Eidt舉例 – Naqeeb

回答

0

您可以使用各種功能成分/鏈模式:

例子:

function chain() { 
    const fns = Array.prototype.slice.call(arguments); 

    return function (result) { 
    return fns.reduce((result, fn) => fn.call(this, result), result); 
    }; 
}; 

chained = chain(before, main, after); 
chained();