Created
February 19, 2014 18:09
-
-
Save paul-jean/9097826 to your computer and use it in GitHub Desktop.
Playing with scopes 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
| var g = 5; | |
| console.log("Global value of g = " + g); // g: 5 | |
| var x = function() { | |
| g = 10; | |
| }; | |
| var y = new x(); | |
| console.log("After y = new x(), g = " + g); // g: 10 | |
| console.log("After y = new x(), y.g = " + y.g); // y.g: undefined | |
| // ^^^ because x is referring to global g | |
| var g = 5; | |
| console.log("** Reset g ** "); | |
| console.log("Global value of g = " + g); // g: 5 | |
| var z = function() { | |
| this.g = 7; | |
| }; | |
| var y = new z(); | |
| console.log("After y = new z(), g = " + g); // g: 5 | |
| console.log("After y = new z(), y.g = " + y.g); // z.g = 7 | |
| // ^^^ because z binds g to z's local scope using "this" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment