Привет, учусь писать элегантный код javascript на простых примерах. Чтобы вы изменили в этом коде, чтобы он, по-вашему, стал лучше? Спасибо.
(function () {
"use strict";
/**
* This function selects all elements on the web pagen by name of tag
* and applies to each of the callback function.
*
* The first param - the tag of elements.
*
* The second param - the name of a function or an anonymous function
* that will handle each found element.
*
* The third param: if the function is a method of object
* and it works with the other properties of the object
* then need to pass the object in the third argument.
*
* @param {string} tagName
* @param {function} callback
* @param {object} object
* @returns {undefined}
*/
var processElementsByTagName = function (tagName, callback, object) {
if (arguments.length < 2) {
throw new Error('Not enough arguments');
}
if (typeof arguments[0] !== 'string') {
throw new Error('The first argument should be an element tag name');
}
var els = document.getElementsByTagName(tagName),
length = els.length,
i = 0;
//if the second argument is the name of the method
if (typeof arguments[1] !== 'function') {
if (typeof arguments[1] !== 'string') {
throw new Error('The second argument must be a function or method name of object');
}
if (typeof arguments[2] !== 'object') {
throw new Error('The third argument must be an object');
}
if (!(arguments[1] in arguments[2])) {
throw new Error('This method does not exist in the object');
}
while (i < length) {
object[callback](els[i]);
i += 1;
}
}
//If the second param is a function
while (i < length) {
callback(els[i]);
i += 1;
}
};
//select all the elements <strong/>, and hide them
//with the use of an anonymous callback function
processElementsByTagName('strong', function (el) {
el.style.display = "none";
});
//And now try to pass an object method
/**
* Some class.
*
* @constructor
* @this {Handler}
* @param {string} color
*/
function Handler(color) {
this.color = color;
}
//The class has a method that accesses a property of the class (color).
Handler.prototype.highligh = function (el) {
el.style.color = this.color;
};
var handler = new Handler('yellow');
//Select all the <span/> elements
//and change the color of the text in each element
processElementsByTagName('span', 'highligh', handler);
}());