Prototype Pattern
Using JS's native prototype object for good program structure.
HTML
<a href="#" id="go">Go</a>
JavaScript
(function(){ // keep following code out of global scope
"use strict"; //don't let me do anything stupid
// class/constructor
var Car = function (engine){
this.engine = engine;
};
Car.prototype = {
start: function(){ /// function in memory once
alert('Started engine: ' + this.engine);
},
stop: function(){
alert('Stopped engine: ' + this.engine);
// start() here wouldn’t work (changes context of ‘this’)
}
};
document.getElementById("go").onclick = function(e){
e.preventDefault();
var car1 = new Car('V8');
car1.start();
car1.stop();
var car2 = new Car('V6');
car2.start();
car2.stop();
};
})();