0

演示:http: //jsfiddle.net/3WpNG/17/

我只是在制作一个框架(出于学习目的),我正在尝试添加一个 forEach 方法,所以当我调用ezWork().class('big').forEach(function(element) { console.log(element) });

它会做它应该做的事情,但我收到错误,任何信息都会很棒,这是我到目前为止的代码:

var ezWork = (function (win, doc) {

    function EzWork(element) {
        this.element = this.iD(element);
    }

    EzWork.prototype = {
        iD: function (element) {
            return document.getElementById(element);
        },

        on: function (event, callback, override) {
            var attach = window.hasOwnProperty('addEventListener'),
                meth = attach ? 'attachEvent' : 'addEventListener',
                prefix = attach ? 'on' : '';
            if (!override) {
                this.element[meth](prefix + event, callback, false);
            } else {
                this['on' + event] = callback;
            }
            return this;
        },
        class: function(element) {
         return doc.getElementsByClassName(element);   
        },

        forEach: function() {
            if(!Array.prototype.forEach) {
                Array.prototype.forEach = function(fn, scope) {
                    for(var i = 0, len = this.length; i < len ; i += 1) {
                         fn.call(scope, this[i], i, this);
                    }
                }
            }
        }
    };
    //
    return function (element) {
        return new EzWork(element);
    }
})(window, document);

console.log(ezWork().class('button'));

ezWork().class('button').forEach(function(element) {
    console.log(element);
});

Error: Uncaught TypeError: Object #<NodeList> has no method 'forEach'

4

1 回答 1

1

下次最好使用控制台。从那里开始,错误就很清楚了。

for(var i = 0; len = this.length; i < len ; i += 1)
//           ^---- this should be a comma

这是一个粗略的包装示例:

function EzWork(element) {
    //stores the data into an instance property
    this.element = element;
}

EzWork.prototype = {
    class: function (element) {
        //wraps the result into the instance and returns the instance
        return new EzWork(doc.getElementsByClassName(element));
    },
    forEach: function (fn) {

        var instance = this;

        //run through the data in the instance
        for (var i = 0, len = instance.element.length; i < len; i += 1) {
            fn.call(instance.element, instance.element[i], i, instance.element);
        }

    }
};
于 2013-04-15T21:37:23.573 回答