Last active
March 2, 2020 15:03
-
-
Save r3dm1ke/2ccb683fa8c252004d339d582537d4b8 to your computer and use it in GitHub Desktop.
Understanding this keyword in JS
This file contains hidden or 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
| const myObject = { | |
| a: 'b', | |
| b: 'c', | |
| doStuff: function() { | |
| // Here, this refers to myObject | |
| console.log(this.a + this.b); | |
| } | |
| } | |
| myObject.doStuff(); // bc | |
| // BUT: | |
| const anotherObject = { | |
| a: 'abacaba', | |
| b: '!' | |
| }; | |
| anotherObject.doStuff = myObject.doStuff; | |
| anotherObject.doStuff(); // abacaba! | |
| // Arrow functions do not have their own this and refer to the outer one: | |
| const arrowObject = { | |
| a: 'b', | |
| // here, this refers to the root function (file itself), which has no idea about a | |
| doMoreStuff: () => console.log(this.a) | |
| }; | |
| arrowObject.doMoreStuff(); // undefined |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment