Some recent work has pushed me into scoping my javascript more consciously. There is a lot of usage of this
on a local level that can make things all sorts of confusing. There are multiple avenues to properly scope your javascript through your functions, but keeping this
scoped properly to use in other scopes gets complicated. I use two different methods and am unsure which is best:
assigning to a new variable
Can now be used inside other functions as _this
when you also need the specific function's this
scope.
var _this = this;
using .bind(this)
This invokes the function with a specified scope, so you can set up your function with .bind()
coming directly after defining it.
function myFunction(e) {
// things
this.doSomething();
}.bind(this);
That really works? Feels weird.
So now I'm wondering where else you can run a function with the proper scope. Say I call myFunction()
from an eventListener:
this.element.addEventListener('click', myFunction, false);
Instead of calling .bind()
on the function level, can I call it on the callback level within the event listener?
this.element.addEventListener('click', myFunction.bind(this), false);
So many questions. So little scope.
Interesting that some functions have this option built into their arguments. If you look at the
Array.prototype.forEach()
method you'll see it can be passed as thethisArg
to specify thethis
scope.