在这段代码中
if (direction === 'up') {
for (key in elements) {
if (elements.hasOwnProperty(key)) {
elements[key].style.opacity = statics.elapsed / max_time;
}
}
} else if (direction === 'down') {
for (key in elements) {
if (elements.hasOwnProperty(key)) {
elements[key].style.opacity = (max_time - statics.elapsed) / max_time;
}
}
}
我想抽象出这个常见的成语:
for (key in elements) {
if (elements.hasOwnProperty(key)) {
// function using elements[key] and outside parameters
}
}
所以我可以简单地写
manyElements(element, function () {
});
我将如何编写函数原型作为起点。我的猜测是。
function manyElements (elements, the_function) {
for (key in elements) {
if (elements.hasOwnProperty(key)) {
the_function();
}
}
}
但我需要访问外部参数,传递这些参数的最佳方法是什么?一般来说,抽象出这段代码是个好主意吗?
似乎我必须单独传递每个参数,从而违背了制作通用功能的目的。
我不喜欢不使用外部库,除了相关性。这里的每个答案是 lodash 实现:
片段 1
function forEach(collection, callback, thisArg) {
if (callback && typeof thisArg == 'undefined' && isArray(collection)) {
var index = -1,
length = collection.length;
while (++index < length) {
if (callback(collection[index], index, collection) === false) {
break;
}
}
} else {
each(collection, callback, thisArg);
}
return collection;
}
片段 2
var each = createIterator(eachIteratorOptions);
片段 3
function createIterator() {
var data = {
'arrayLoop': '',
'bottom': '',
'hasDontEnumBug': hasDontEnumBug,
'isKeysFast': isKeysFast,
'objectLoop': '',
'nonEnumArgs': nonEnumArgs,
'noCharByIndex': noCharByIndex,
'shadowed': shadowed,
'top': '',
'useHas': true
};
// merge options into a template data object
for (var object, index = 0; object = arguments[index]; index++) {
for (var key in object) {
data[key] = object[key];
}
}
var args = data.args;
data.firstArg = /^[^,]+/.exec(args)[0];
// create the function factory
var factory = Function(
'createCallback, hasOwnProperty, isArguments, isString, objectTypes, ' +
'nativeKeys, propertyIsEnumerable',
'return function(' + args + ') {\n' + iteratorTemplate(data) + '\n}'
);
// return the compiled function
return factory(
createCallback, hasOwnProperty, isArguments, isString, objectTypes,
nativeKeys, propertyIsEnumerable
);
}