Created
March 4, 2015 20:46
-
-
Save gilbert/287130055fbe4b44cef6 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
// English Example: | |
// Do your daily duties: | |
// Make me breakfast | |
// Do my laundry | |
// Walk my dog | |
// Make me breakfast: | |
// Turn on the stove | |
// Get out the eggs | |
// Crack them open | |
// Put them on the pan | |
// Wait until they're cooked | |
// Serve them | |
// Example 2 | |
// Goal: Create an array that looks like [3,4,5,6,7] | |
var array = [] | |
array.push(3) | |
array.push(4) | |
array.push(5) | |
array.push(6) | |
array.push(7) | |
// ---------- | |
// This is an abstraction over the above five lines. | |
for (var i=3; i <= 7; i++) { | |
array.push(i) | |
} | |
// ---------- | |
// This is an abstraction over the above for loop. | |
// It is also more reusable, since we can use it for | |
// any range of numbers, not just 3 and 7 | |
function range (start, end) { | |
var results = [] | |
for (var i=start; i <= end; i++) { | |
results.push(i) | |
} | |
return results | |
} | |
var array = range(3, 7) |
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
// Class (with encapsulation) | |
function Person (initName, initAge) { | |
// State (contained in an instance) | |
var name = initName | |
var age = initAge | |
this.incrementAge = function () { | |
age += 1 | |
} | |
this.getAge = function () { | |
return age | |
} | |
} | |
// create instances of Person | |
var alice = new Person('alice', 20) | |
var bob = new Person('bob', 19) | |
alice.incrementAge() | |
alice.age //=> undefined | |
// Works | |
var f = alice.incrementAge | |
window.f() | |
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
// Class (no encapsulation) | |
function Person (name, age) { | |
// State (contained in an instance) | |
this.name = name | |
this.age = age | |
this.incrementAge = function () { | |
this.age += 1 | |
} | |
} | |
// create instances of Person | |
var alice = new Person('alice', 20) | |
var bob = new Person('bob', 19) | |
alice.incrementAge() | |
// Doesn't work | |
// var f = alice.incrementAge | |
// window.f() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment