javascript – ES6类:在方法上应用’addEventListener’访问’this’
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – ES6类:在方法上应用’addEventListener’访问’this’,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1706字,纯文字阅读大概需要3分钟。
内容图文
![javascript – ES6类:在方法上应用’addEventListener’访问’this’](/upload/InfoBanner/zyjiaocheng/713/1f1a8f4ba0de4f6db7d2deb69281e60a.jpg)
参见英文答案 > How to access the correct `this` inside a callback? 10个
在这个es6脚本中,click事件不起作用,因为使用this.elm(< div>)调用sayHello方法.
如何在不松散范围的情况下将事件与方法相关联?
class player{
constructor (name) {
this.name = name;
this.elm = document.createElement('div');
this.elm.addEventListener('click', this.sayHello);
}
sayHello() {
console.log(this.name + ' say: "hello!"'); // 'undefined say 'hello!"';
}
kill() {
console.log(`RIP ${this.name} :'(`);
this.elm.addClass('dead');
this.elm.removeEventListener('click', this.sayHello);
}
}
解决方法:
这是一个普遍的JS问题,但它的核心是
this.elm.addEventListener('click', this.sayHello);
没有什么不同
var fn = this.sayHello;
this.elm.addEventListener('click', fn);
您正在将函数作为事件处理程序传递,但未确保在调用fn时将其设置为所需的值.在ES5中执行此操作的最简单方法是
this.elm.addEventListener('click', this.sayHello.bind(this));
或者在ES6中,使用箭头功能:
this.elm.addEventListener('click', evt => this.sayHello(evt));
但请注意,这两种解决方案都会破坏你的(已经略微破坏)的逻辑,因为
this.elm.removeEventListener('click', /* what? */);
您没有任何对您附加的函数的引用,因此您无法删除事件处理程序.
我建议两个选择:
// Create a new function that is bound, and give it a new name
// so that the 'this.sayHello()' call still works.
this.boundSayHello = evt => this.sayHello(evt);
this.elm.addEventListener('click', this.boundSayHello);
this.elm.removeEventListener('click', this.boundSayHello);
要么
// Bind the function with the same name and use `.bind` instead of the
// arrow function option.
this.sayHello = this.sayHello.bind(this);
this.elm.addEventListener('click', this.sayHello);
this.elm.removeEventListener('click', this.sayHello);
内容总结
以上是互联网集市为您收集整理的javascript – ES6类:在方法上应用’addEventListener’访问’this’全部内容,希望文章能够帮你解决javascript – ES6类:在方法上应用’addEventListener’访问’this’所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。