例如,我的系統中有一個平方函式,例如
function square(a) {
console.log(a);
return a * a;
}
這個平方函式在程式的生命周期中被多次呼叫,例如
square(5);
square(1);
square(2);
square(3);
現在的問題是我想獲取在任何給定時間呼叫的時間平方函式的計數,例如square.count應該回傳4
該解決方案不僅應該與平方函式一起作業,而且應該是可擴展的并且適用于系統中可用的其他函式。例如,如果我也有一個power(a,n)函式,那么我應該能夠通過類似的方式獲得冪函式的計數power.count
uj5u.com熱心網友回復:
您可以創建一個包裝目標函式并記錄該資訊的函式,如下所示:
function addCounter(fn) {
// Create a wrapper function
const newfn = function(...args) {
// In the wrapper, increment the count
newfn.count;
// Call original and return its return value
return fn.apply(this, args);
};
// Set up the count
newfn.count = 0;
// Ensure the new function's `length` matches the original
// (in case you have anything relying on it)
Object.defineProperty(newfn, "length", {
value: fn.length,
configurable: true,
});
// Return the new function
return newfn;
}
然后你像這樣替換函式:
square = addCounter(square);
現在,無論何時呼叫它,計數器都會遞增。
現場示例:
顯示代碼片段
function addCounter(fn) {
// Create a wrapper function
const newfn = function(...args) {
// In the wrapper, increment the count
newfn.count;
// Call original and return its return value
return fn.apply(this, args);
};
// Set up the count
newfn.count = 0;
// Ensure the new function's `length` matches the original
// (in case you have anything relying on it)
Object.defineProperty(newfn, "length", {
value: fn.length,
configurable: true,
});
// Return the new function
return newfn;
}
function square(a) {
console.log(a);
return a * a;
}
square = addCounter(square);
console.log(square(5));
console.log(`square.count = ${square.count}`);
console.log(square(1));
console.log(`square.count = ${square.count}`);
console.log(square(2));
console.log(`square.count = ${square.count}`);
console.log(square(3));
console.log(`square.count = ${square.count}`);
.as-console-wrapper {
max-height: 100% !important;
}
您可能不會為此煩惱,length代碼查看lengthon 函式是不尋常的,但它的存在是為了徹底。(你必須使用definePropertyto 設定length。它是一個只讀屬性,但它是可配置的,所以我們可以重新定義它。)
只是為了完整性:如果任何東西在您更新它之前已經獲取了它自己對該函式的參考,那么通過該其他參考的呼叫將不會被計算在內。但這很不尋常,希望您不會碰巧有代碼這樣做。您可能會遇到的一個問題是,如果您正在使用 CommonJS 模塊(直接使用,或者因為您的捆綁器將 JavaScript 標準模塊語法轉換為 CommonJS,就像某些人所做的那樣)并且在替換它之前將其匯出(這似乎不太可能) . 出現問題的原因是對于 CommonJS 模塊,匯出的是函式參考的副本。這不是標準 JavaScript 模塊的問題 ( import/export) 原生使用,因為匯入是對原始匯出的實時系結,所以上面的方法可以正常作業。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/417635.html
標籤:
上一篇:使用資料陣列創建卡片反應
下一篇:檢測價值的按鈕
