我正在嘗試爲當前項目上的交互式日曆編寫ES6類。ES6類 - 從事件處理程序中調用方法
的Class看起來類似於下面:
class Calendar {
constructor (s) {
this.eventButtons = s.eventButtons;
this.eventButtons.forEach(button => button.addEventListener('click', this.method1);
this.eventBoxes = s.eventBoxes;
method1 (e) {
e.preventDefault();
this.method2(e.target.href);
}
method2 (url) {
console.log(url);
}
}
export default Calendar;
我知道,「這個」關鍵字的上下文從構造改爲已被點擊方法1函數內的按鈕。但是我不知道如何保持按鈕和構造函數的上下文在同一個函數中。我嘗試將按鈕事件監聽器代碼更改爲以下代碼:
this.eventButtons.forEach(button => button.addEventListener('click', this.method1).bind(this);
但是,這只是將「this」關鍵字的上下文切換到構造函數而不是按鈕。我需要在我的功能中使用兩者。
任何想法?我希望這是一個很常見的問題?
的[無法調用它在ES6在Node.js的限定它的一類內的方法](可能的複製https://stackoverflow.com/questions/39621821/cannot-call-a-method-within- a-class-it-defined-it-in-es6-in-node-js) – noahnu