简体   繁体   English

在没有匿名 function 的情况下,无法从导入的 class 将函数分配给“onclick”?

[英]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).我有两个 js 文件:index.js 和 TaskList.js(我在其中创建了 class “TaskList”,然后导出到 index.js)。

I want to assign method "sortTaskAsc()" of class "TaskList" to event "onclick" on a button.我想将 class“TaskList”的方法“sortTaskAsc()”分配给按钮上的事件“onclick”。 So in index.js, when I write like this with anonymous function, it works:所以在 index.js 中,当我用匿名 function 这样写时,它可以工作:

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.我注意到,当我对 index.js 中的函数使用第二种方式时,它们都可以工作。 But when I use with functions from an imported class, they won't.但是当我使用来自导入的 class 的函数时,它们不会。 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. TaskList 的方法 sortTaskAsc 与相关元素绑定,因为您使用“函数”语句。

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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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