Enumerable provides a large set of useful methods for enumerations, that is, objects that act as collections of values. It is a cornerstone of Prototype.
Enumerable is what we like to call a module: a consistent set of methods intended not for independent use, but for mixin: incorporation into other objects that “fit” with it.
Quite a few objects, in Prototype, mix Enumerable in already. The most visible cases are Array and Hash, but you'll find it in less obvious spots as well, such as in ObjectRange and various DOM- or AJAX-related objects.
上面這短話的意思大概就是說Enumerable是Prototype框架的基石,而Enumerable不單獨使用,在Prototype中其它對象mix了Enumerable里面的方法,這樣就可以在這些對象上應用Enumerable的方法,這樣的對象有:Array,Hash,ObjectRange,還有一些和DOM,AJAX相關的對象。
個人理解Enumerable相當于C++中的抽象類的概念,其它類可以繼承自這個類,并且實現Enumerable里面的抽象方法"_each",并且可以覆蓋其它的方法,而Enumerable本身卻不可以實例化,只可以實例化它的子類。
下面看一下如何通過Enumerable來寫自己的類:
代碼如下:
var YourObject = Class.create();
Object.extend(YourObject.prototype, Enumerable); Object.extend(YourObject.prototype, {
initialize: function() {
// with whatever constructor arguments you need
// Your construction code
},
_each: function(iterator) {
// Your iteration code, invoking iterator at every turn
},
// Your other methods here, including Enumerable overrides
});
可以看出最重要的就是實現_each方法,initialize方法就相當于構造函數,如果不需要外部傳進來什么參數,完全可以省略。下面我自己寫了一個產生隨機數數組的類,非常簡單,有許多不完善的地方,這里只做演示用:
代碼如下:
//創建RandomArray類
var RandomArray = Class.create();
//mixin Enumerable
Object.extend(RandomArray.prototype, Enumerable);
//實現_each和所需方法
Object.extend(RandomArray.prototype, {
initialize: function(min,max,count) {
this.min=min;
this.max=max;
this.count=count;
this._numbers=[];
this._createRandomArray();
},
_each: function(iterator) {
var index=this.count;
while(index-->0){
iterator(this._numbers[index]);
}
},
//產生隨機數數組
_createRandomArray:function(){
新聞熱點
疑難解答
圖片精選