我的代码可以工作,但我被教导将'this‘绑定到事件侦听器函数。在我的web组件类构造函数中,我在阴影根目录中有一个按钮。在构造函数中,我还在按钮上添加了单击事件侦听器,并继续将function函数定义为箭头函数,即this.clickHandler = (e) => {...}。但是,我没有将'this‘绑定到事件侦听器函数,我只是使用了this.button.addEventListener('click', this.clickHandler)。代码似乎工作得很好,而且,和我之前的许多其他代码一样,我确信,我还需要一些关于绑定“this”的指导。非常感谢。
发布于 2022-11-26 10:46:20
创建测试代码以查看所有选项:
<my-component></my-component>
<script>
customElements.define("my-component", class extends HTMLElement{
constructor(){
function element ({ tag, ...props} ) {
return Object.assign(document.createElement(tag), props);
}
super().attachShadow({mode:"open"})
.append(this.button = element({
tag : "button",
innerText : "click me!",
onclick : (evt) => this.clicked(evt,1) // 1
}));
this.button.addEventListener("click", (evt) => this.clicked(evt,2) ); // 2
this.button.addEventListener("click", this.clicked ); // 3
this.button.addEventListener("click", this.clicked.bind(this) ); // 4
}
clicked( evt, nr="no parameters!" ){
console.log(evt.type, nr , "scope:", this.nodeName);
}
})
</script>
onclick Event Handler Property创建了更好的可读性代码;但您只能为每个元素分配一个。
click处理程序。IMHO,不要用它!因为初级团队成员不理解为什么行为不同于正常的类方法。
当您在代码中看到它时,它(同样是IMHO)是旧的see符号。
- it indicates something special is going on
- or the developer is old and never learned or appreciated new _fat-arrow_ syntax with _lexical_ scope
- or the developer is inexperienced, and copy-pasted code
- or ...注意:您可以使用bind传递参数。但是,它将将预先加到绑定方法中;
这意味着在clicked(evt)中,evt参数现在成为第一个参数.对初中生来说更混乱了。
非常深入地研究“这”:How does the "this" keyword work, and when should it be used?
https://stackoverflow.com/questions/74579940
复制相似问题