Created
October 17, 2016 16:46
-
-
Save mrandrewmills/a1efdadc69a1638ec6763b5eda53ae69 to your computer and use it in GitHub Desktop.
Notes and examples for the two approaches to JS OOP
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
// JavaScript OOP Notes & Examples | |
// The "Singleton" Approach | |
var fizzbuzz = { | |
start: 1, | |
stop: 100, | |
modFizz: 3, | |
modBuzz: 5, | |
sayFizz: "fizz", | |
sayBuzz: "buzz", | |
play: function() { | |
"use strict"; | |
var x, sayThis, results; | |
x = ""; | |
results = []; | |
for (x = this.start; x <= this.stop; x++) { | |
sayThis = ""; | |
if (x % this.modFizz === 0) { sayThis += this.sayFizz; } | |
if (x % this.modBuzz === 0) { sayThis += this.sayBuzz; } | |
if (sayThis == "") { sayThis = x; } | |
results[x] = sayThis; | |
} | |
console.table(results); | |
} | |
} | |
// example invocations of the Singleton | |
fizzbuzz.play(); | |
fizzbuzz.stop = 10000; | |
fizzbuzz.sayFizz = "FIZZ!"; | |
fizzbuzz.play(); | |
// The Constructor Function approach | |
function fizzbuzz(start, stop, modFizz, modBuzz, sayFizz, sayBuzz) { | |
// our properties, use passed values or assign default values | |
this.start = start || 1; | |
this.stop = stop || 100; | |
this.modFizz = modFizz || 3; | |
this.modBuzz = modBuzz || 5; | |
this.sayFizz = sayFizz || "fizz"; | |
this.sayBuzz = sayBuzz || "buzz"; | |
// our methods | |
this.play = function() { | |
"use strict"; | |
var x, sayThis, results; | |
x = ""; | |
results = []; | |
for (x = this.start; x <= this.stop; x++) { | |
sayThis = ""; | |
if (x % this.modFizz === 0) { sayThis += this.sayFizz; } | |
if (x % this.modBuzz === 0) { sayThis += this.sayBuzz; } | |
if (sayThis == "") { sayThis = x; } | |
results[x] = sayThis; | |
} | |
console.table(results); | |
} | |
} | |
// examples of instantiation via Constructor Function | |
var yourFB = new fizzbuzz(); | |
var myFB = new fizzbuzz(1, 1000, 30, 50, "fizz!", "buzz!"); | |
yourFB.play(); | |
myFB.play(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment