Skip to content

Instantly share code, notes, and snippets.

@gilbert
Created March 4, 2015 20:46
Show Gist options
  • Save gilbert/287130055fbe4b44cef6 to your computer and use it in GitHub Desktop.
Save gilbert/287130055fbe4b44cef6 to your computer and use it in GitHub Desktop.
// 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)
// 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()
// 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