.bind()
has to be called AFTER the object you want it to be bound to has already been created and when you’re in the right context to have a reference to the desired object. You are calling .bind()
when your code is first loaded. That will not have a meaningful value for this
. Instead, change your code to this:
function MyPlugin() {
this.hello = 'hello';
// save bound function so you can use it to remove the listener later
this.fn = this.clicked.bind(this);
document.addEventListener('click', this.fn);
this.clicked('e');
}
MyPlugin.prototype.clicked = function(e) {
console.log(this.hello, e);
}
// method that will remove the event listener
MyPlugin.prototype.stopClick = function() {
document.removeEventListener('click', this.fn);
}
var plugin1 = new MyPlugin();
Notice in this fixed version that .bind(this)
is called ONLY when we already have this
that corresponds to our current object.
In your version, you were calling clicked.bind(this)
when your code was first loaded and this
would have a global value which in strict mode would be undefined
and in non-strict mode in the browser would be window
. The object that you will create with new MyPlugin()
doesn’t even exist yet when you were calling clicked.bind(this)
so there’s obviously no way that this
could contain the appropriate value.
If you want to be able to remove the event listener later, then just store the bound listener so you can use it later.
6
solved ‘this’ doesn’t work when assign and bind to a variable