Skip to content

Instantly share code, notes, and snippets.

@mapsam
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mapsam/9ac81e0df2240b66ec21 to your computer and use it in GitHub Desktop.
Save mapsam/9ac81e0df2240b66ec21 to your computer and use it in GitHub Desktop.
_this = this vs. .bind(this)

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.

@ranchodeluxe
Copy link

correct, but all your ondrop inner references have to be resolved

function ondrop(e) {
  e = e || event;
  e.preventDefault();
  this.className = '';
  files = e.dataTransfer.files;
  this._readFiles(files);
}.bind(this);

I think you might be able to apply it to the event listener too! Not quite sure. You should try that. It's less fugly.

@mapsam
Copy link
Author

mapsam commented Mar 16, 2015

So how do you work with this in the ondrop() function AND the global this when you need both?

@mapsam
Copy link
Author

mapsam commented Mar 16, 2015

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 the thisArg to specify the this scope.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment