-
-
Save rmw/ef5b4ba73b7480776759 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
// 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