国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

Prototype Enumerable對象 學習第1/2頁

2024-05-06 14:14:42
字體:
來源:轉載
供稿:網友

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(){

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 安溪县| 南岸区| 泗水县| 凤凰县| 海兴县| 天水市| 金昌市| 罗山县| 政和县| 米林县| 林周县| 石泉县| 裕民县| 芜湖市| 旌德县| 高淳县| 唐海县| 鹿泉市| 平罗县| 调兵山市| 长汀县| 黄陵县| 五华县| 城步| 宁都县| 柏乡县| 哈尔滨市| 佛教| 宁武县| 右玉县| 阿鲁科尔沁旗| 象山县| 常宁市| 襄樊市| 金平| 津市市| 宜兰县| 阜宁县| 东乡县| 广东省| 蚌埠市|