Skip to content

Instantly share code, notes, and snippets.

@ndelage
Created April 30, 2014 14:08
Show Gist options
  • Save ndelage/f5678c2fd9d4d216aa86 to your computer and use it in GitHub Desktop.
Save ndelage/f5678c2fd9d4d216aa86 to your computer and use it in GitHub Desktop.
JS Scope
// How many globals?
function Person(name) {
this.name = name;
}
function greeting(person) {
console.log("Hello " + person.name);
}
var roger = new Person("Roger");
greeting(roger);
// Creating Scope. How do we create a scope?
var innerState = 12;
console.log(innerState); // should print 12
console.log(innerState); // should print undefined or raise not defined error
// Functions create scope in JS. What if we nest them?
function processData(data) {
data.forEach(processItem);
function processItem(item) {
var reversed = item.split("").reverse().join("");
console.log(reversed);
}
}
processData(["Apple", "Orange", "Pear"]);
processData("Peach");
// Can we have more than one variable by the same name?
// This is called shadowing.
var city = "Chicago";
// ?
var city = "NYC";
console.log(city) // should print 'NYC'
// ?
console.log(city) // should print 'Chicago'
// this
console.log(this);
function firstFunction() {
console.log("Hello World!");
console.log(this);
}
function Person() {
this.name = "Jane Doe";
console.log(this);
}
Person.prototype.save = function() {
$.post("/people", {name: this.name}, function(resp) {
this.id = resp.id;
}, "json");
}
firstFunction.apply(new Person());
// hoisting
function hoisted() {
console.log(name);
var name = "Roger";
}
// Wacky Stuff ahead...execution contexts with functions
//
function makeCounter() {
// `i` is only accessible inside `makeCounter`.
var i = 0;
return function() {
console.log( ++i );
};
}
// Note that `counter` and `counter2` each have their own scoped `i`.
var counter = makeCounter();
counter(); // logs: 1
counter(); // logs: 2
var counter2 = makeCounter();
counter2(); // logs: 1
counter2(); // logs: 2
// IIFE Immediately Invoked Function Expressions
var elems = $('a');
for(var i=0; i<elems.length; i++) {
$(elems[i]).on('click', function(e){
e.preventDefault();
alert( 'I am link #' + i );
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment