當我在JavaScript中編寫函數包裝器(例如:throttle
或debounce
函數)時,我希望能夠檢查'裝飾'函數,並且仍然能夠知道底層函數是什麼。取throttle
的實現爲例:在JavaScript中重寫function.toString時應該擔心嗎?
function throttle(fn, time) {
var handle;
var execute = function() {
handle = null;
fn.apply(this, arguments);
};
var throttled = function() {
if(!handle) {
handle = setTimeout(execute.bind(this), time);
}
};
throttled.toString = function() {
return fn.toString() + "\n// throttled to " + time + "ms";
};
return throttled;
}
var makeAjax = throttle(function(callback) {
$.getJSON("/path", callback);
}, 500);
console.log(makeAjax);
的console.log
來電顯示:
function (callback) {
$.getJSON("/path", callback);
}
// throttled to 500ms
由於throttle
用戶我更關心了一大堆關於我把它比它的內部throttled
功能。
但是,在重寫原生函數時,我總是感到有點不安。在執行此操作時是否存在任何我應該擔心的合規性和/或性能問題?
隱式轉換可能是一個問題。但是你可能不會有隱式投射函數的情況。 –
任何會調用'fn.toString()'的東西都是用於日誌記錄或動態重新編譯,所以我認爲你會爲此罰款。特別是因爲你不覆蓋'Function.prototype.toString'。 – Esailija
@Esailija你是什麼意思動態重新編譯? –