Created
May 12, 2016 05:26
-
-
Save jacklynrose/7a010d9af3795b529aa9079edca90825 to your computer and use it in GitHub Desktop.
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
// Set on window | |
this.foobar = "V1" | |
//=> (result) "V1" | |
console.log(this.foobar) | |
//=> (output) V1 | |
//=> (result) undefined | |
// Uses window | |
(() => { | |
console.log(this.foobar); | |
})() | |
//=> (output) V1 | |
//=> (result) undefined | |
// Uses window | |
(function() { console.log(this.foobar); })() | |
//=> (output) V1 | |
//=> (result) undefined | |
// Uses window | |
(function() { | |
(function() { console.log(this.foobar); })(); | |
})() | |
//=> (output) V1 | |
//=> (result) undefined | |
// Uses window | |
(function() { | |
(() => { console.log(this.foobar); })(); | |
})() | |
//=> (output) V1 | |
//=> (result) undefined | |
// Sets on window, uses that | |
(function() { | |
this.foobar = "V2"; | |
(() => { console.log(this.foobar); })(); | |
})() | |
//=> (output) V2 | |
//=> (result) undefined | |
// Resetting | |
this.foobar = "V1" | |
//=> (result) "V1" | |
// Sets and uses window | |
(function() { | |
this.foobar = "V2"; | |
(function() { console.log(this.foobar); })(); | |
})() | |
//=> (output) V2 | |
//=> (result) undefined | |
// Now where functions get weird because constructors and methods | |
function MyThing1() { | |
this.foobar = "V3"; | |
(function() { console.log(this.foobar); })(); | |
} | |
//=> (result) undefined | |
// Run the constructor and oh wait what? Uses window | |
new MyThing1(); | |
//=> (output) V2 | |
//=> (result) MyThing1 {foobar: "V3"} | |
// What if we use arrow functions? | |
function MyThing2() { | |
this.foobar = "V4"; | |
(() => { console.log(this.foobar); })(); | |
} | |
//=> (result) undefined | |
// That makes more sense now, it uses the thing above it | |
new MyThing2(); | |
//=> (output) V4 | |
//=> (result) MyThing2 {foobar: "V4"} | |
// This is how we make them act the same by binding "this" | |
function MyThing3() { | |
this.foobar = "V5"; | |
(function() { console.log(this.foobar); }).bind(this)(); | |
} | |
//=> (result) undefined | |
// Now it acts the same as the arrow function | |
new MyThing3(); | |
//=> (output) V5 | |
//=> (result) MyThing3 {foobar: "V5"} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Another example of weirdness is if we try to force an arrow function to a context. eg:
Gives us
"V2"
in the console because we assign the function withinMyThing2
to the first object,thing
. But if we try to do it with arrow functions....We get "V3". The arrow function basically says "No thanks" to your assignment and sticks with its guns. What a badass.