Skip to content

Instantly share code, notes, and snippets.

@srsandy
Created February 23, 2021 10:14
Show Gist options
  • Save srsandy/1824802e4f28ab3c4fb1f3991186df91 to your computer and use it in GitHub Desktop.
Save srsandy/1824802e4f28ab3c4fb1f3991186df91 to your computer and use it in GitHub Desktop.
All `this` variations
// GLOBAL
console.log(this); //--> window
// FUNCTION
function discoverThis() {
console.log(this); //--> window
}
discoverThis();
// OBJECT
const obj = {
name: "This",
discoverThis: function () {
console.log(this); //--> object
},
discoverThis2: () => {
console.log(this); //--> window
},
discoverThis3: function () {
return function () {
console.log(this); //--> window
};
},
discoverThis4: function () {
return () => {
console.log(this); //--> object
};
},
discoverThis5: () => {
return function () {
// both arrow and function keyword
console.log(this); //--> window
};
},
discoverThis6: function () {
function tellThis() {
console.log(this); //--> window
}
tellThis();
},
};
obj.discoverThis();
obj.discoverThis6();
// ARROW FUNCTION
const discoverThis = () => {
console.log(this); //--> window
};
discoverThis();
// CLOSURE
function discoverThis() {
return () => {
// both arrow and function keyword
console.log(this); //--> window
};
}
discoverThis()();
// IIFE
(() => {
// both arrow and function keyword
console.log(this); //--> window
})();
@srsandy
Copy link
Author

srsandy commented Feb 23, 2021

Open for Suggestions and improvements :)

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