OOP Patterns: Constructor/Prototype
This uses a pseudo-classical pattern that tries to emulate the building of classes using classical inheritance like Java or other classical languages.
HTML
<ul id="unordered-list">
<li id="one">I'm number … </li>
<li id="two">I'm number … </li>
<li id="three">Who's my mommy?</li>
<li id="four">I do nothing :(</li>
</ul>
CSS
p {
text-align: center;
margin: 20px 0 0;
}
ul {
margin: 25px 0;
}
li {
text-align: center;
margin: 10px auto;
padding: 5px;
width: 200px;
background: #ddd;
outline: 1px solid #999;
border: 1px solid #eee;
border-right-color: #bbb;
border-bottom-color: #bbb;
}
li:hover {
border-left-color: #bbb;
border-top-color: #bbb;
cursor: pointer;
}
JavaScript
// Create an "array" so that we can cherry pick out elements
var listArray = document.getElementsByTagName('li');
/*************************************\
**** Constructor/Prototype Pattern ****
\*************************************/
var ListId = function (item) {
item = item || {};
this.element = item;
// We have to check if item has the getAttribute method
if (typeof item.getAttribute === 'function') {
this.elementId = item.getAttribute('id');
} else {
// console.log(item + "doesn't have the getAttribute method");
}
};
ListId.prototype = {
constructor: ListId,
getId: function () {
var element = this.element,
elementId = this.elementId;
$(element).click(function () {
alert(elementId);
});
}
}; // End of Constructor/Prototype
// Create a child object that inherits
// from the parent.
// Have to use the *new* method
var retreiveOne = new ListId(listArray[0]),
retreiveTwo = new ListId(listArray[1]);
retreiveOne.getId(); // logs "one" upon click
retreiveTwo.getId(); // logs "one" upon click
// "Extend" the original object
var WhatId = function (item) {
this.element = item;
// We have to check if item has the getAttribute method
if (typeof item.getAttribute === 'function') {
this.elementId = item.parentNode.getAttribute('id');
} else {
// console.log(item + "doesn't have the getAttribute method");
}
};
// Tie it back to the original constructor
WhatId.prototype = new ListId();
// Create a grandchild object that inherits
// from the parent and the grandparent.
// Needs the *new* method
var retreiveThree = new WhatId(listArray[2]);
retreiveThree.getId(); // logs "one" upon click