1
我在JavaScript中有一個功能,同時使用this
和捕獲參數:使用函數參數,這在同樣的方法
var Watcher = function() {
var callbacks = [];
var currentValue = null;
this.watch = function (callback) {
callbacks.push(callback);
if (currentValue) {
callback.apply(null, currentValue);
}
};
this.notify = function() {
currentValue = arguments;
for (var i = 0; i < callbacks.length; i++) {
callbacks[i].apply(null, arguments);
}
};
}
我想這個更改爲打字稿類。我想出了什麼,就是:
class Watcher {
private currentValue: any[] = null;
private callbacks: Function[] = [];
watch = (callback: Function) => {
this.callbacks.push(callback);
if (this.currentValue) {
callback.apply(null, this.currentValue);
}
}
// cannot access arguments
notify =() => {
this.currentValue = /*arguments?*/;
for (var callback of this.callbacks) {
callback.apply(null, /*arguments?*/);
}
}
// cannot acces this
notify() {
/*this?*/.currentValue = arguments;
for (var callback of /*this?*/.callbacks) {
callback.apply(null, arguments);
}
}
}
如何使一個功能,我可以都使用this
參考去我的領域,和傳遞給我的函數的參數?
您可以在第二個通知,方法訪問它,不要擔心。 –
從我所瞭解的情況來看,取決於notify方法的調用方式可能會中斷,而TypeScript通過使用閉包語法來解決這個問題。 – Jorn