|
<div class="container"> |
|
<h1>JS OOP Template</h1> |
|
|
|
<p><strong>Special thanks to <a href="https://github.com/bluebaron">Braxton</a> for his editorial review!</strong> See the associated <a href="http://codepen.io/reesington/blog/javascript-best-practices/">blog post</a> for all the details.</p> |
|
|
|
<p>Demonstrates use of the module design pattern to leverage closures for privacy. Shows a decent way of achieving prototype-based constructor chains for inheritance -- also explains how the .call(...) function plays a crucial role there. Does NOT use a logical OR to assign default value since then an intentional false-y value could be skipped over an unintended truth-y value (try <code>var bar = arg || 5;</code> in your console).</p> |
|
|
|
<pre><code class="javascript"> |
|
(function() { // Anonymous function encapsulating all code as per the module pattern. |
|
'use strict'; // Ensures code is much more secure and optimized by making fewer assumptions. |
|
|
|
var Entertainer = function(firstName, lastName) { // "Constructor." |
|
// Properties: |
|
this.firstName = firstName; |
|
this.lastName = lastName; |
|
|
|
// Methods -- they don't go here for performance reasons! |
|
}; |
|
|
|
// Rather, Entertainer's methods go here for performance reasons: |
|
Entertainer.prototype.breathe = function() { |
|
alert(this.firstName + ' ' + this.lastName + ' breathed.'); |
|
}; |
|
|
|
var Singer = function(firstName, lastName, voiceType) { // "Constructor." |
|
Entertainer.call(this, firstName, lastName); /* Inherit properties and methods from Entertainer. |
|
Note that first argument above clones Entertainer's properties into Singer. |
|
The other arguments pass data into the cloned, corresponding properties. |
|
voiceType isn't passed since it's specific to Singer and not handled by the more generic Entertainer. */ |
|
|
|
// Properties: |
|
this.voiceType = voiceType; |
|
|
|
// Methods -- they don't go here for performance reasons! |
|
}; |
|
|
|
// Set Singer's prototype to Entertainer: |
|
Singer.prototype = Object.create(Entertainer.prototype); |
|
|
|
// That last statement was needed to properly set Singer's methods here: |
|
Singer.prototype.sing = function() { |
|
alert(this.firstName + ' ' + this.lastName + ' sang like a ' + this.voiceType + '.'); |
|
}; |
|
|
|
var reese = new Singer('Reese', 'Louis', 'Baritone'); |
|
|
|
// Uncomment the following function calls to see how this works: |
|
//reese.breathe(); |
|
//reese.sing(); |
|
})(); |
|
</code></pre> |
|
</div> |