Last active
March 29, 2018 12:33
-
-
Save t-palmer/c700145ab945e08a0b559b0709e3b656 to your computer and use it in GitHub Desktop.
An example of lexical this in arrow functions.
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 ThisTester { | |
constructor () { | |
this.testValue = 'ThisTester Class'; | |
} | |
// in arrow functions we can freely use "this". | |
thisArrowTest() { | |
// define a local function like we might use in a promise or callback | |
let myFunction = (x) => console.log('arrow "this" works:', this.testValue) | |
myFunction(); | |
} | |
// When we didn't have "lexical this" we had to store this using "self" | |
thisTest() { | |
// We use self to store the "this" of the class | |
let self = this; | |
// define a local function like we might use in a promise or callback | |
function myLocalFunction () { | |
// The typical paradigm was to create a variable called self and use that | |
console.log('self works:', self.testValue); | |
// It is fine to use functions like this but be careful about "this" | |
console.log('the function "this" is not the "this" of the Class, so it fails.'); | |
console.log('function this fails', this.testValue); | |
} | |
myLocalFunction(); | |
} | |
} | |
const myTester = new ThisTester(); | |
console.log('TESTING: thisArrowTest'); | |
myTester.thisArrowTest(); | |
console.log(''); | |
console.log('TESTING: thisTest'); | |
myTester.thisTest(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment