为什么我的模型框架的forEach原型不起作用?

时间:2013-04-15 21:33:11

标签: javascript

演示: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'

1 个答案:

答案 0 :(得分:1)

下次最好使用控制台。错误就像那天一样清晰。

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

这是包装的a rough example

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);
        }

    }
};