在点击事件监听器中使用时,这不是一个功能

Vik*_*ram 1 javascript

我正在处理javascript文件,并具有以下代码

class test(){
    constructor(){
    }
    showBox(){
        var countBlock = document.createElement("div");
        document.body.appendChild(countBlock); 
        countBlock.addEventListener('click', function(){
            this.showList()
        });
    }
    showList(){
        console.log('Element clicked')
    }
}
Run Code Online (Sandbox Code Playgroud)

除非单击元素,否则代码工作正常,当我单击它时,它显示 this.showList() is not a function

不确定如何解决

jo_*_*_va 7

使用箭头功能

countBlock.addEventListener('click', () => this.showList());
Run Code Online (Sandbox Code Playgroud)

箭头函数按词法绑定它们的上下文,因此this引用原始上下文,原始上下文是包含箭头函数的代码的上下文。

或使用常规函数,但将其绑定this到您的函数:

countBlock.addEventListener('click', function () { this.showList() }.bind(this));
// or shorter, no need to wrap it in a function:
countBlock.addEventListener('click', this.showList.bind(this));
Run Code Online (Sandbox Code Playgroud)

您可以this 在此处了解更多信息。

这是一个基于您的代码的示例:

countBlock.addEventListener('click', () => this.showList());
Run Code Online (Sandbox Code Playgroud)
countBlock.addEventListener('click', function () { this.showList() }.bind(this));
// or shorter, no need to wrap it in a function:
countBlock.addEventListener('click', this.showList.bind(this));
Run Code Online (Sandbox Code Playgroud)