Java Script Structuring - Prototype Pattern
Cons:
There are no cons as such for this java script pattern. The concept of "this" might get confusing in certain cases.
Pro :
1. all methods of different instances refer to same instance in memory
2. extending methods is very simple
by FrictionlessPulley
December 18, 2013
HTML
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
<div class="container">
<div class="page-header">
<h1>Prototype Pattern</h1>
</div>
<div class="panel panel-primary">
<div class="panel-heading"> <span class="glyphicon glyphicon-wrench"></span> Settings</div>
<div class="panel-body">
<p>Each Panel below represents two instances of <code>Animal</code> objects. The <i>Speak</i> button invokes the <code>Animal.Speak </code> method on each instance. The <i>Switch Speak Definition</i> button updates the definition of the <code>Speak</code> method <em>only</em> for the <code>Dog</code> instance.</p>
<input type="button" id="change" class="btn btn-primary" value="Switch Speak Definition" />
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">Animal</div>
<div class="panel-body">
<p>invokes <code>animal.Speak</code> method</p>
<!-- This is the HTML DIV which the AnimalSpeak button updates -->
<div id="animalSpeak"></div>
<input type="button" id="animalSpeakButton" class="btn btn-primary" value="Speak" />
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">Dog</div>
<div class="panel-body">
<p>invokes <code>dog.Speak</code> method</p>
<!-- This is the HTML DIV which the DogSpeak button updates -->
<div id="dogSpeak"></div>
<input type="button" id="dogSpeakButton" class="btn btn-primary" value="Speak" />
</div>
</div>
</div>
JavaScript
/* Simple Animal with a function to Speak */
var Animal = function (elementIdentifier) {
this.element = $(elementIdentifier);
this.count = 0;
};
/* Animal Speak function.
1. increments count by 1
2. updates element with comments
*/
Animal.prototype.Speak = function () {
this.count = this.count + 1;
this.element.addClass('alert alert-success');
this.element.html('Animal Speaking.....<span class="badge">' + this.count + '</span> time.');
};
$(function () {
// Make Animal Speak
var animal = new Animal('#animalSpeak');
$('#animalSpeakButton').on('click', function () {
animal.Speak();
});
// Make Dog Speak
var dog = new Animal('#dogSpeak');
$('#dogSpeakButton').on('click', function () {
dog.Speak();
});
// Change Animal Speak working
$('#change').on('click', function () {
Animal.prototype.Speak = function () {
this.count = this.count + 1;
this.element.addClass('alert alert-success');
this.element.html('Dog Speaking.....<span class="badge">' + this.count + '</span> time.');
};
alert('Changed Definition of Animal.prototype.Speak');
});
});