0

I have two js files: index.js and TaskList.js (in which I created class "TaskList" then export to index.js).

I want to assign method "sortTaskAsc()" of class "TaskList" to event "onclick" on a button. So in index.js, when I write like this with anonymous function, it works:

getElementByID("btn-sortDown").onclick = () => {taskList.sortTaskAsc()}

but when I want to try this way, it doesn't work any more:

getElementByID("btn-sortDown").onclick = taskList.sortTaskAsc

I notice that when I use the second way for the functions inside index.js, they all work. But when I use with functions from an imported class, they won't. In console tab it says some error about "undefined".

Please help me understand the reason for this. Thank you guys.

kevinV
  • 33
  • 1
  • 7

1 Answers1

0

Method sortTaskAsc of TaskList is binded with relevant element because of you use "function" statement.

class TaskList {
    sortTaskAsc() {
        console.log(this);
    }
}

let taskList = new TaskList();

getElementByID("btn-sortDown").onclick = taskList.sortTaskAsc
//onclick binds the function with element btn-sortDown. `this` gives an element.

getElementByID("btn-sortDown").onclick = () => taskList.sortTaskAsc()
//Arrow functions are not binded with anything.
//Therefore `this` doesn't be corrupted and it gives the class.
Raven Murphy
  • 181
  • 10