演示:http://jsfiddle.net/3WpNG/17/爲什麼我的模型框架的forEach原型不起作用?
我只是做了一個框架(爲了便於學習),我嘗試添加一個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'
你什麼錯誤(除了明顯的語法錯誤)?同時查看https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach#Compatibility – Bergi
@Bergi http://jsfiddle.net/3WpNG/18/檢查console.log '未捕獲的類型錯誤:對象#沒有forEach'方法' –
Datsik
您的.class()方法確實從'doc.getElementsByClassName()'返回'NodeList',它不會有forEach方法,因爲它不是陣!你不想爲了可鏈接性而返回另一個'EzWork'實例嗎? – Bergi