將「defer()」裝飾器加入函式
重要性:4
將方法 defer(ms)
加入所有函式的原型,它會傳回一個包裝器,延遲 ms
毫秒後再呼叫。
以下是它的運作方式範例
function f(a, b) {
alert( a + b );
}
f.defer(1000)(1, 2); // shows 3 after 1 second
請注意,參數應傳遞給原始函式。
Function.prototype.defer = function(ms) {
let f = this;
return function(...args) {
setTimeout(() => f.apply(this, args), ms);
}
};
// check it
function f(a, b) {
alert( a + b );
}
f.defer(1000)(1, 2); // shows 3 after 1 sec
請注意:我們在 f.apply
中使用 this
,讓我們的裝飾器能用於物件方法。
因此,如果包裝器函式作為物件方法呼叫,則 this
會傳遞給原始方法 f
。
Function.prototype.defer = function(ms) {
let f = this;
return function(...args) {
setTimeout(() => f.apply(this, args), ms);
}
};
let user = {
name: "John",
sayHi() {
alert(this.name);
}
}
user.sayHi = user.sayHi.defer(1000);
user.sayHi();