Created
February 23, 2021 10:14
-
-
Save srsandy/1824802e4f28ab3c4fb1f3991186df91 to your computer and use it in GitHub Desktop.
All `this` variations
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
// 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 | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Open for Suggestions and improvements :)