JS類的實現

來源:互聯網
上載者:User

標籤:

1個月前寫過,重新寫一遍

//類的實現,一個參數建立類,兩個參數繼承類var Klass = function (parent, options) {    var        hasOwn = Object.prototype.hasOwnProperty,    //中間函數避免執行父類建構函式        Func = function () {        },    //mixin淺拷貝        extend = function (receiving, giving) {            var k;            for (k in giving) {                if (hasOwn.call(giving, k)) {                    receiving[k] = giving[k];                }            }        },    //返回的子類        Child = function (opt) {            extend(this, opt);        };    //參數check    if (arguments.length === 0 || arguments.length > 2) throw new Error("只接受1個或2個參數");    //只傳入一個參數對象    if (typeof parent !== ‘function‘) {        options = parent;        parent = null;    }    //繼承父類    if (parent) {        Func.prototype = parent.prototype;        Child.prototype = new Func();        Child.prototype.constructor = Child;    }    //添加options    extend(Child.prototype, options);    return Child;};//測試var Person = Klass({        getName: function () {            return this.name;        },        say: function() {            console.log("hello world");        },        fav: ‘Js‘    }),    Player = Klass(Person, {        play: function () {            console.log("i‘m playing " + this.game);        }    }),    player = new Player({        name: ‘bobo‘,        game: ‘Dota2‘    });player.play();  // "i‘m playing Dota2"player.say();   // "hello world"console.log(player.getName() + " " + player.fav);   //"bobo Js"

 

JS類的實現

聯繫我們

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