Hallo,
Vielleicht sollte jobo erst einmal versuchen, einfachen, klassischen OO-Code zu schreiben, verständliche APIs zu entwerfen und dann stärker funktional zu programmieren. Denn diesen Code finde ich alles andere als elegant.
functional
function cycleColors(elemStyle, rgbVals, rgbRanges) {
function createNextColorFunc(v, r) {
var value = v,
max = v,
range = r,
dir = 1;
return function () {
if (value <= max - range || value >= max) {
dir *= -1;
}
value += dir;
return value;
};
}
var nextRed = createNextColorFunc(rgbVals[0], rgbRanges[0]),
nextGreen = createNextColorFunc(rgbVals[1], rgbRanges[1]),
nextBlue = createNextColorFunc(rgbVals[2], rgbRanges[2]);
return function () {
elemStyle.backgroundColor = "RGB(" + nextRed() + "," + nextGreen() + "," + nextBlue() + ")";
};
}
window.onload = function () {
window.setInterval(cycleColors(document.body.style, [255, 168, 136], [55, 10, 16]), 120);
};
vs.
OO
var MyBgColor = {
red : false,
green : false,
blue : false,
style : false,
createColorObj : function (value, range) {
return {
"value": value,
"max" : value,
"range" : range,
"dir" : 1
};
},
init : function (style, red, green, blue) {
this.style = style;
this.red = this.createColorObj(red.start, red.range);
this.green = this.createColorObj(green.start, green.range);
this.blue = this.createColorObj(blue.start, blue.range);
},
nextVal : function (colorName) {
if (this[colorName].value <= this[colorName].max - this[colorName].range
|| this[colorName].value >= this[colorName].max) {
this[colorName].dir *= -1;
}
this[colorName].value += this[colorName].dir;
return this[colorName].value;
},
change : function () {
this.style.backgroundColor = "RGB(" + this.nextVal("red") + "," + this.nextVal("green") + "," + this.nextVal("blue") + ")";
}
};
window.onload = function () {
MyBgColor.init(document.body.style, {start : 255, range : 55}, {start : 168, range : 10}, {start : 136, range : 16});
window.setInterval(function () {MyBgColor.change(); }, 120);
};
Benamung ähnlich, Parameter variieren etwas.
35 vs. 25 Zeilen. Der funktionale Ansatz arbeitet mit privaten Variablen, was ja eigentlich doch sinnig erscheint (s. a. Crockford: http://javascript.crockford.com/private.html "This pattern of public, private, and privileged members is possible because JavaScript has closures. What this means is that an inner function always has access to the vars and parameters of its outer function, even after the outer function has returned. This is an extremely powerful property of the language.")
Gruß
jobo