[英]Javascript class method binding not working
I have this class:我有这门课:
class test{ constructor(){ document.addEventListener('click', handle); this.handle = this.handle.bind(this); } handle(){ console.log(this); //returns document element } } new test()
I'm binding this
to the handle event but it still returns the document element.我this
绑定到句柄事件,但它仍然返回文档元素。 I tried using arrow functions and it works but I want to know if I can do it without using arrow functions...我尝试使用箭头函数并且它有效,但我想知道是否可以在不使用箭头函数的情况下做到这一点......
Assign before the binding.在绑定之前分配。
You're thinking that a reference will be modified, however, you're only assigning a new value to that attribute rather than modifying it.您认为引用将被修改,但是,您只是为该属性分配了一个新值,而不是修改它。
class test { constructor() { this.eleFromEstack = "Test"; // Just a test! this.handle = this.handle.bind(this); document.addEventListener('click', this.handle); } handle() { console.log(this); } } new test();
<h1>Click!!</h1>
Bind the this
value when supplying the handler
function to the addEventListener
callback.在向addEventListener
回调提供handler
函数时绑定this
值。
class Test{ field = "hello" handle(){ console.log(this); //returns document element } constructor(){ document.querySelector("#container").addEventListener('click', this.handle.bind(this)); } } let test = new Test();
<div id="container">test</div>
没关系,我的本地服务器正在使用更新的代码缓存 JS 文件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.