I'm trying to create a custom module. I'm using prototype
to add additional methods. The module will have an event, in which I will have to access a method from the module with 'this
'. I will do that using bind
.
I ran into a slight problem. I created a method, then using prototype
, I assigned the method to a variable
with the bind
method. The problem is, 'this
' isn't the one I passed through bind
. Here's the sample code:
function MyPlugin() {
this.hello = 'hello'
document.addEventListener('click', this.clickedBinded);
this.clickedBinded('e');
}
MyPlugin.prototype.clickedBinded = clicked.bind(this);
function clicked(e) {
console.log(this.hello, e);
}
var plugin1 = new MyPlugin();
How can I get clickedBinded
have this
as this
? Meaning, I don't want this
to be Window
, I want it to be MyPlugin
.
Update
The reason why I did: MyPlugin.prototype.clickedBinded = clicked.bind(this)
and not: document.addEventListener('click', this.clicked.bind(this));
, is because I'm going to have to remove the event at some point. And as this answer sais, if you're using bind
in an event handler, and you want to remove the event, you have to assign the method with bind
to a variable
.