Created
December 30, 2017 19:11
-
-
Save ihatecsv/50820f4169f2ccbeb8ed718795e71f68 to your computer and use it in GitHub Desktop.
Proper way to preserve "this"?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ExampleClass{ | |
constructor(a){ | |
this.a = a; | |
} | |
someMethod(){ | |
const outerThis = this; | |
someOtherMethod(function(b){ | |
outerThis.a = b; | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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