2013-04-15 61 views
0

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

+0

你什麼錯誤(除了明顯的語法錯誤)?同時查看https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach#Compatibility – Bergi

+0

@Bergi http://jsfiddle.net/3WpNG/18/檢查console.log '未捕獲的類型錯誤:對象#沒有forEach'方法' – Datsik

+0

您的.class()方法確實從'doc.getElementsByClassName()'返回'NodeList',它不會有forEach方法,因爲它不是陣!你不想爲了可鏈接性而返回另一個'EzWork'實例嗎? – Bergi

回答

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

    } 
}; 
+0

http://jsfiddle.net/3WpNG/18/謝謝你的收穫,但我得到一個錯誤,檢查控制檯日誌,forEach沒有定義? – Datsik

+0

@XCritics我剛剛從你貼的小提琴中將分號改爲逗號。 [**沒有像那樣發生**。](http://jsfiddle.net/3WpNG/19/)你還在那裏改變了什麼? – Joseph

+0

在這個評論中檢查新的小提琴 – Datsik

相關問題