Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
295 views
in Technique[技术] by (71.8m points)

javascript - ES6 Class: access to 'this' with 'addEventListener' applied on method


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is a general JS issue, but the core of it is that

this.elm.addEventListener('click', this.sayHello);

is no different than

var fn = this.sayHello;
this.elm.addEventListener('click', fn);

You are passing a function as the event handler, but have not ensured that when fn is called that this will be set to your desired value. The easiest way to do this in ES5 would be

this.elm.addEventListener('click', this.sayHello.bind(this));

or in ES6, using an arrow function:

this.elm.addEventListener('click', evt => this.sayHello(evt));

Note however that both of these solutions will break your (already slightly broken) logic in kill because

this.elm.removeEventListener('click', /* what? */);

You don't have any reference to the function that you attached anymore, so you have no way of removing the event handler.

I'd suggest two options:

// 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);

or

// 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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...