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.
correct, but all your
ondropinner references have to be resolvedI think you might be able to apply it to the event listener too! Not quite sure. You should try that. It's less fugly.