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