Passing A Bound Object Method In Javascript
For a Firefox extension, I'm trying to do the following: Setup an object with two methods and a field/property/attribute One of the methods has to be able to call the other method
Solution 1:
Use the ES5 bind
function:
varObj = {
field: null,
a: function() { }
b: function() {
this.a = 'x';
this.a(); //Note: not sure what you're trying to do, but calling a string like a function won't work.
}
}
window.addEventListener('mouseup', Obj.b.bind(Obj), false);
Solution 2:
bind
is definitely a good approach. However, notice that addEventListener
method can accept object that implements the EventListener interface, instead of a function:
varObj = {
field: null,
a: function() { },
b: function() {
this.field = 'x'; // if you overrides `a` you can't call itthis.a();
},
handleEvent: function(event) {
switch(event.type) {
case"mouseup":
this.b();
break;
}
}
}
window.addEventListener('mouseup', Obj, false);
This can be useful if you have multiple events related to Obj
, and/or if you have multiple instances of the same object (not your case).
Post a Comment for "Passing A Bound Object Method In Javascript"