5. OO JS

Created Saturday 14 June 2014

function Rectangle (w, h) {
this.width = w;
this.height = h;
}
Rectangle.prototype.area = function () {
return this.width * this.height;
}
Rectangle.prototype.perimeter = function () {
return (2 * this.width) + (2 * this.height);
}
Rectangle.EMPTY = new Rectangle(0, 0);
Rectangle.Max = function (a, b) {
if (a.area() == b.area()) return null;
else if (a.area() > b.area()) return a;
else return b;
}
Rectangle.prototype.toString = function () {
return "Rectangle of width: " + this.width + "& height: " + this.height;
}
Rectangle.prototype.valueOf = function () {
return this.area();
Rectangle.prototype.equals = function (oRect) {
return (this.width == oRect.width && this.height == oRect.height);
}
Rectangle.prototype.compareTo = function(oRect) {
return (this.area() - oRect.area());
}
myObject instanceof myClass
myRect instanceof Rectangle // true
myRect instanceof Object // true
myRect instanceof Array // false
function DepthRectangle(w, h, d) {
Rectangle.call(this, w, h);
this.depth = d;
}
DepthRectangle.prototype = new Rectangle();
DepthRectangle.prototype.constructor = DepthRectangle;
DepthRectangle.prototype.volume = function () {
return (this.area() * this.depth);
}
DepthRectangle.prototype.toString = function () {
return "DepthRectangle with width: " + this.width + " & height: " + this.height + " & depth: " + this.depth;
}
Array.prototype.longestElement = function () {
var maxLength = 0;
for (var i = 0; i < this.length; i++) {
if (this[i].toString().length > maxLength)
maxLength = this[i].toString().length;
}
return maxLength;
}
var testArray = new Array(0, 1, "test", "big string", new Date());
alert(testArray.longestElement());
function BetterSelect(oSelList) {
this.objSelectList = oSelList;
}
BetterSelect.prototype.clear = function () {
this.objSelectList.options.length = 0;
}
BetterSelect.prototype.fill = function (aValues) {
this.clear();
for (var i = 0; i < aValues.length; i++) {
this.objSelectList.options[i] = new Option(aValues[i]);
}
}
BetterSelect.prototype.getCount = function () {
return this.objSelectList.options.length;
}
BetterSelect.prototype.find = function (strToFind, bSelect) {
var indx = -1;
this.objSelectList.options.selectedIndex = -1;
for (var i = 0; i < this.getCount(); i++) {
if (this.objSelectList.options[i].text == strToFind) {
indx = i;
if (bSelect)
this.objSelectList.options.selectedIndex = i;
}
}
}
var mySelectList = null;
window.onload = function () {
mySelectList = new BetterSelect(document.getElementById('theList'));
}
function fillList() {
mySelectList.fill(new Array("one", "two", "three", "four", "five"));
}
function findIt() {
mySelectList.find(document.getElementById('txtToFind'), true);
}
Button1.addEventListener("click", fillList(), false);
Button4.addEventListener("click", mySelectList.clear(), false);
Button2.addEventListener("click", alert(mySelectList.getCount()), false);
Button3.addEventListener("click", findIt(), false);



Backlinks: