在 JavaScript 类中声明事件处理程序的正确方法是什么?

问题描述 投票:0回答:1

我在 MDN 上查看,类的方法如下所示:

class Foo {
    method1 (){
      // content of method1
    }
}

但是我发现这对于事件处理程序来说并不好

<!doctype html>
<html lang="en">
<head>
    <title>test</title>
</head>
<body>
    <div class="settings">
        <div>
            <label for="cb1">checkbox</label>
            <input id="cb1" type="checkbox"></input>
        </div>
    </div>
    
    <script>
        'use strict'
        class TEST{
            box = null;
            info = {content: {blah: "blah"}};
            
            init (){
                this.box = window.document.querySelector(".settings");
                this.box.addEventListener("change", this.handler);
                this.box.addEventListener("change", this.handler2);
            }
            
            handler = e=> {
                console.log("handler this: %o", this);
                console.log("handler info: %o", this.info.content);
            }
            handler2 (e) {
                console.log("handler2 this: %o", this);
                console.log("handler2 info: %o", this.info.content);
            }
        }
        let t = new TEST();
        t.init();
    </script>
</body>
</html>

在上面的测试页面中,点击复选框,结果是

阅读箭头函数的范围,然后我明白为什么会有区别。但是使用箭头函数来声明类的方法看起来很奇怪,我做对了吗?

更重要的是,因为我不喜欢在一个类中有两种函数样式,所以如果可能的话,我更喜欢对所有其他方法使用箭头函数,但我不确定这是否适用于

constructor
或者它是否有任何功能潜在的故障或安全问题

请问对此有何意见?

javascript class scope event-handling arrow-functions
1个回答
0
投票

当您将方法作为参数传递时,您基本上是在没有上下文的情况下单独传递它(在我们的例子中

this
)。有几个修复方法可以实现这一目标:

使用

.bind()

this.box.addEventListener("change", this.handler.bind(this));

使用箭头功能:

this.box.addEventListener("change", e => this.handler(e));
© www.soinside.com 2019 - 2024. All rights reserved.