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(){
新闻热点
疑难解答
图片精选