Skip to content

Instantly share code, notes, and snippets.

@r3dm1ke
Last active March 2, 2020 15:03
Show Gist options
  • Select an option

  • Save r3dm1ke/2ccb683fa8c252004d339d582537d4b8 to your computer and use it in GitHub Desktop.

Select an option

Save r3dm1ke/2ccb683fa8c252004d339d582537d4b8 to your computer and use it in GitHub Desktop.
Understanding this keyword in JS
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