Skip to content

Instantly share code, notes, and snippets.

@paul-jean
Created February 19, 2014 18:09
Show Gist options
  • Select an option

  • Save paul-jean/9097826 to your computer and use it in GitHub Desktop.

Select an option

Save paul-jean/9097826 to your computer and use it in GitHub Desktop.
Playing with scopes in JS
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