各大類庫的類工廠

來源:互聯網
上載者:User
文章目錄
  • Prototype.js1.6之後的類工廠
  • dojo的類工廠:
  • YUI的類工廠
  • Simple JavaScript Inheritance
  • mootools的類工廠
  • mass Framework的類工廠

類工廠是指用於產生類的函數,我們不能每寫一個類都重複以下代碼,要好好封裝一下!

var F = function(){}F.prototype = SuperClass.prototype;SubClass.prototype = new F;SubClass.prototype.constructor = SubClass
Prototype.js1.6之後的類工廠
var Animal = Class.create({  initialize: function(name, sound) {    this.name  = name;    this.sound = sound;  },  speak: function() {    alert(this.name + " says: " + this.sound + "!");  }});// subclassing Animalvar Snake = Class.create(Animal, {  initialize: function($super, name) {    $super(name, 'hissssssssss');  }});var ringneck = new Snake("Ringneck");ringneck.speak();//-> alerts "Ringneck says: hissssssssss!"var rattlesnake = new Snake("Rattler");rattlesnake.speak();//-> alerts "Rattler says: hissssssssss!"// mixing-in Enumerablevar AnimalPen = Class.create(Enumerable, {    initialize: function() {    var args = $A(arguments);    if (!args.all( function(arg) { return arg instanceof Animal }))      throw "Only animals in here!"    this.animals = args;  },  // implement _each to use Enumerable methods  _each: function(iterator) {    return this.animals._each(iterator);  }});var snakePen = new AnimalPen(ringneck, rattlesnake);snakePen.invoke('speak');//-> alerts "Ringneck says: hissssssssss!"//-> alerts "Rattler says: hissssssssss!"

通過Class.create來建立一個類與連結一個父類與其他材料構成一個子類。想調用同名父方法,需要在此方法的參數中傳入一個$super參數。

dojo的類工廠:
var F = function(){}F.prototype = SuperClass.prototype;SubClass.prototype = new F();SubClassprototype.constructor = SubClass

Prototype.js1.6之後的類定義

dojo.declare(    "TestClass",    null,    {        id:"",        info: { name : "",age:""},        staticValue:{count:0},        constructor : function(id,name,age) {            this.id=id;            this.info.name=name;            this.info.age=age                         this.staticValue.count++;               }    });

它有三個參數,類名,父類,與一個對象,裡麵包含構建這個類的材料。

YUI的類工廠
// http://blog.csdn.net/phphot/article/details/4325823YUI().use('oop', function(Y) {    var Bird = function(name) {        this.name = name;    };    Bird.prototype.getName = function(){ return this.name; };    var Chicken = function(name) {        Chicken.superclass.constructor.call(this, name);    };    Y.extend(Chicken, Bird);    var chicken = new Chicken('Tom');    Y.log(chicken.getName());});

supperclass 有兩個作用:一是可以用來調用父類的方法,二是可以通過 supperclass.constructor 調用父類的建構函式。一舉兩得.

不過它相對於其他類工廠來說是非常原始的,只負責連結子類與父類。

Simple JavaScript Inheritance

這是jquery作者搞的東西

// http://ejohn.org/blog/simple-javascript-inheritance/var Person = Class.extend({  init: function(isDancing){    this.dancing = isDancing;  },  dance: function(){    return this.dancing;  }});var Ninja = Person.extend({  init: function(){    this._super( false );  },  dance: function(){    // Call the inherited version of dance()    return this._super();  },  swingSword: function(){    return true;  }});var p = new Person(true);p.dance(); // => truevar n = new Ninja();n.dance(); // => falsen.swingSword(); // => true// Should all be truep instanceof Person && p instanceof Class &&n instanceof Ninja && n instanceof Person && n instanceof Class

由Class.create來建立父類,然後通過父類的extend方法加個屬性包建立子類.

mootools的類工廠
//  http://hmking.blog.51cto.com/3135992/682098    var Animal = new Class({         initialize: function (age) {             this.age = age;         }     });     var Cat = new Class({         Extends: Animal,         initialize: function (name, age) {             this.parent(age); // calls initalize method of Animal class             this.name = name;         }     });          var cat = new Cat('Micia', 20);     console.log(cat.name); // 'Micia'     console.log(cat.age); // 20 

它應該是所有架構中最複雜也是最強大的,涉及的API就有Mutator Extends Implements還有從Type繼承過來的extend implement,它內部拷貝父類屬性還用到了深拷貝!

Extends: 可以實現父類,也可以調用父類初始化 this.parent()。而且會覆蓋父類定義的變數或者函數。

Implements: 實現父類,子類不可以覆蓋父類的方法或者變數。即使子類定義與父類相同的變數或者函數,也會被父類取代掉。

implement: 是用於調整已經建立好的類的原型成員.

extend: 調用子類(非其執行個體)的extend方法建立一個新的子類.

mass Framework的類工廠
//http://rubylouvre.github.com/doc/index.html$.require("class,spec", function() {     var Shape = $.factory({        init: function(len) {            $.log(len)            this.length = len || 0;        },        getLength: function() {            return this.length;        },        setLength: function(len) {            this.length = len;        },        getArea: function() {            throw "Subclasses must implement this method"        }    })     var Triangle = $.factory({        inherit: Shape,        init: function(len, hei) { //len屬性在父類中已定義,這裡可以省去            this.height = hei || 0;        },        getArea: function() {            return this.length * this.height / 2        }    })    var Square = $.factory({        inherit: Shape,        getArea: function() {            return this.length * this.length;        }    });    var t = new Triangle(3, 4)    $.log(t.getArea(), true)    var s = new Square(4)    $.log(s.getArea(), true)});

$.factory為類工廠,參數為一個普通對象,此對象擁有如下可選屬性

  • init為新類的構造器,沒有預設傳入空函數進去
  • inherit為新類的父類
  • extend的參數是一個對象或對象數組,不管怎麼樣,這些對象的屬性只是為新類添加靜態成員,或者說它們是添加到類之上的
  • implement的參數是一個對象或對象數組或類(類即函數),這些對象的屬性只是為新類添加執行個體成員,或者說它們是添加到類的原型上.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.