简体   繁体   中英

Cannot assign functions to "onclick" from imported class without anonymous function?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM