在多个对象上执行单个功能

时间:2013-04-01 12:26:59

标签: javascript

是否可以通过例如对多个对象执行单个功能。将它们分组。我想做的是:

{object1, object2, object3}.toFront();

2 个答案:

答案 0 :(得分:2)

一种简单的方法:

var nodes = [node.rectangle1, node.text, node.rectangle2];
for (var i = 0; i < nodes.length; i++) {
    nodes[i].toFront();
}

如果您使用underscore并且简洁:

_.invoke([node.rectangle1, node.text, node.rectangle2], 'toFront');

如果您想要返回值,可以使用map,或者如果您只是需要一些额外的处理,请查看each

编辑(完成此操作):

你也可以使用内置forEach(如果你不关心某些浏览器或者你选择填充它),其方式与下划线each非常相似:

[node.rectangle1, node.text, node.rectangle2].forEach(function(el) {
    el.toFront();
});

答案 1 :(得分:1)

虽然您已经接受了答案,但这可以通过JavaScript 1.6 / ECMAScript 5 th 版本以类似的方式实现:

function logElementID(element, index, array) {
    var el = array[index],
        prop = el.textContent ? 'textContent' : 'innerText';
    el[prop] = el.id;
}

[document.getElementById('one'), document.getElementById('two')].forEach(logElementID);

JS Fiddle demo

或者通过扩展Object原型:

function doStuff (el) {
    console.log(el);
};

Object.prototype.actOnGroup = function(func){
    var els = this.length ? this : [this];
    for (var i = 0, len = els.length; i<len; i++){
        func(els[i]);
    }
    return this;
};

document.getElementsByTagName('div').actOnGroup(doStuff);
document.getElementById('one').actOnGroup(doStuff);

JS Fiddle demo

或类似地,扩展Array原型:

function doStuff (el) {
    console.log(el);
};
Array.prototype.actOnGroup = function(func){
    var els = this.length ? this : [this];
    for (var i = 0, len = els.length; i<len; i++){
        func(els[i]);
    }
    return this;
};

[document.getElementById('one'), document.getElementById('two')].actOnGroup(doStuff);

JS Fiddle demo

顺便提一下,如果您希望在没有(相对)最新JavaScript实施的情况下为用户提供forEach()替代方案,则forEach()的Mozilla开发人员网络页面提供以下内容: an]算法100%真实的ECMA-262,第5版':

// Production steps of ECMA-262, Edition 5, 15.4.4.18
// Reference: http://es5.github.com/#x15.4.4.18
if (!Array.prototype.forEach) {

    Array.prototype.forEach = function forEach(callback, thisArg) {

        var T, k;

        if (this == null) {
            throw new TypeError("this is null or not defined");
        }

        // 1. Let O be the result of calling ToObject passing the |this| value as the argument.
        var O = Object(this);

        // 2. Let lenValue be the result of calling the Get internal method of O with the argument "length".
        // 3. Let len be ToUint32(lenValue).
        var len = O.length >>> 0; // Hack to convert O.length to a UInt32

        // 4. If IsCallable(callback) is false, throw a TypeError exception.
        // See: http://es5.github.com/#x9.11
        if ({}.toString.call(callback) !== "[object Function]") {
            throw new TypeError(callback + " is not a function");
        }

        // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
        if (thisArg) {
            T = thisArg;
        }

        // 6. Let k be 0
        k = 0;

        // 7. Repeat, while k < len
        while (k < len) {

            var kValue;

            // a. Let Pk be ToString(k).
            //   This is implicit for LHS operands of the in operator
            // b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk.
            //   This step can be combined with c
            // c. If kPresent is true, then
            if (Object.prototype.hasOwnProperty.call(O, k)) {

                // i. Let kValue be the result of calling the Get internal method of O with argument Pk.
                kValue = O[k];

                // ii. Call the Call internal method of callback with T as the this value and
                // argument list containing kValue, k, and O.
                callback.call(T, kValue, k, O);
            }
            // d. Increase k by 1.
            k++;
        }
        // 8. return undefined
    };
}

从MDN forEach()文章的参考文献(下文)逐字复制; 2013年4月1日,14:30。

参考文献: