Skip to content

Instantly share code, notes, and snippets.

@ihatecsv
Created December 30, 2017 19:11
Show Gist options
  • Save ihatecsv/50820f4169f2ccbeb8ed718795e71f68 to your computer and use it in GitHub Desktop.
Save ihatecsv/50820f4169f2ccbeb8ed718795e71f68 to your computer and use it in GitHub Desktop.
Proper way to preserve "this"?
class ExampleClass{
constructor(a){
this.a = a;
}
someMethod(){
const outerThis = this;
someOtherMethod(function(b){
outerThis.a = b;
});
}
}
@hagb4rd
Copy link

hagb4rd commented Dec 31, 2017

it is valid, and has been done this way before arrow functions were invented. arrow functions don't bind a this accessor, and therefore an outer this would not be shadowed.

someOtherMethod(b=>this.a=b); // they are often used as delegates .. in fact you can, and possibly should use them anywhere you wouldn't use object binding

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