我的類庫功能預覽 ruby風格的繼承機制

來源:互聯網
上載者:User

建立一個新類,使用dom.factory方法,很明顯它是一個Factory 方法,批量生產各種各式的類。

      var MyFirstClass = dom.factory({        message: "hello world",        sayHello: function() {          alert(this.message);        }      });      var obj = new MyFirstClass();      obj.sayHello();//hello world

繼承:

      var Animal = dom.factory({        init: function(name) {          this.name = name;        },        eat: function() {          alert('yummie');        }      });      var Human = dom.factory({        inherit: Animal,        speak: function() {          alert(this.name + ' said bla bla bla');        }      });      var peter = new Human('peter');      peter.eat();//yummie      peter.speak();//peter said bla bla bla      var Pat = dom.factory({        inherit: Human,//注意這裡,使用inherit方法        init: function(name,age) {          this.age = age        }      });      var pat = new Pat('pat',18);      alert(pat.name)//pat      alert(pat.age)//18      pat.speak();//pat said bla bla bla

方法鏈。就是在當前方法調用其父類的同名方法。

     var Girl = dom.factory({        sayHello: function() {          return "Hello there";        }      });      var FancyGirl = dom.factory( {        inherit:Girl,        sayHello: function() {          return "Well, "+ this.$super() +"!";        }      });      var g = new Girl;      alert(g.sayHello());      var f = new FancyGirl;      alert(f.sayHello());

內部方法:

       dom.require("lang");      dom.require("oop")      var Person = dom.oop({        init: function(name){          this.name = name;        },        secret: function(){          return 'I sometimes like girly drinks';        }.protect(),  //定義其為內部方法,只能內部調用        describe: function(){          return "Hi, I'm #{name}. #{secret}. I kid, I kid.".instead({            name: this.name,            secret: this.secret()          });        }      });      var scott = new Person('司徒正美');      // alert(scott.secret());//報錯 The method "secret" cannot be called.      alert(scott.describe());//Hi, I'm Scott. I sometimes like girly drinks. I kid, I kid.

singleton,標識生產的新類為單例類:

      var God = dom.factory({        init:function(name){          this.name = name;          this.alertName = function(){            alert(this.name)          }        },        singleton:true//注意這裡,使用singleton屬性      });      var god = new God("耶和華");      god.alertName();      //alerts 耶和華      var lucifer = new God("撒旦");      lucifer.alertName();   //alerts 耶和華      alert(god === lucifer )//alerts true

alias,別名機制:

      var Array2 = dom.factory({        init:function(){          var args = [].slice.call(arguments);          this.setArray(args);        },        setArray: function (arr) { //把普通對象變成類數組對象,          this.length = 0;        //必須要讓它成為原型方法才可以使用          [].push.apply(this, arr);          return this;        },        toString: function () { //返回一個字串          return [].slice.call(this).toString();        },        valueOf: function () {//獲得裡面的數組對象          return [].slice.call(this);        },        pop:[].pop,        push:[].push,        shift:[].shift,        unshift:[].unshift,        reverse:[].reverse,        indexOf: function(el,index){          var n = this.length,          i = index == null ? 0 : index < 0 ? Math.max(0, n + index) : index;          for (; i < n; i++)            if (i in this && this[i] === el) return i;          return -1;        }      });      Array2.alias("indexOf","contains")      var a = new Array2(1,2,3,4,5);      alert(a)//測試toString方法      alert(a.indexOf(3))      alert(a.contains(3))//測試別名機制

include,包含,類似ruby,添加原型成員。

      var movable = {        run:function(){          alert("能跑")        },        fly:function(){          alert("能飛")        }      }      var recognition  ={        watch:function(){          alert("看東西")        },        smell:function(){          alert("能嗅東西")        }      }      var Robot = dom.factory({        init:function(name,type){          this.name = name;          this.type = name;        },        include:[movable,recognition]      });      var chi = new Robot("小嘰","Chobits") ;      alert(chi.name);      chi.watch();      chi.fly();

extend,擴充,類似ruby,添加類成員。

      var MyClass = dom.factory({});      MyClass.extend({        PI:"3.14",        alert:function(){          alert("這是靜態(類)方法")        },        alertPI:function(){          alert(MyClass.PI);        }      });      MyClass.alert();//這是靜態(類)方法      MyClass.alertPI();//3.14      var m = new MYClass      m.alert()//報錯MYClass is not defined

自擴充與自包含:

      var Module = {        selfIncluded: function(klass) {          klass.prototype.boo = 'boo';        },        selfExtended: function(klass) {          klass.BOO = 'BOO';        }      };      var MyClass = dom.factory({        include: Module,        extend:  Module      });      alert(MyClass.prototype.boo); // -> 'boo'      alert(MyClass.BOO);           // -> 'BOO'
        dom.geometry = {};        var Point = dom.geometry.Point = dom.factory({            init: function(x, y) {                this.x = x*1.0 || 0.0;                this.y = y*1.0 || 0.0;            },            toString: function() {                return this.x + ' ' + this.y;            },            clone: function() {                return new Point(this.x, this.y);            },            eq: function(point) {                return this.x == point.x && this.y == point.y;            },            //移動點到新的位置            offset: function(x, y) {                if (typeof x === 'object') {                    y = x.y;                    x = x.x;                }                this.x += x;                this.y += y;                return this;            },            extend:{                fromString : function(string) {                    var parts = string.split(/\s+/);                    return new Point( parts[0], parts[1] );                }            }        });

添加原型成員。

var movable = {  run:function(){    p("能跑")  },  fly:function(){    p("能飛")  }}var recognition  ={  watch:function(){    p("看東西")  },  smell:function(){    p("能嗅東西")  }}var Robot = oop({  init:function(name,type){    this.name = name;    this.type = name;  },  include:[movable,recognition]});var chi = new Robot("小嘰","Chobits") ;p(chi.name);chi.watch();chi.fly();
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.