一種基於JS原型鏈的類的構造與派生。【原創】

來源:互聯網
上載者:User

標籤:

轉載請註明出處

2016.7.5 by Totooria Hyperion

http://demo.th-shr.com:9999/

 

// 初始化prototype和靜態方法function initClass(constructor,_proto) {    // 配置prototype    for(var key in _proto) {        constructor.prototype[key] = _proto[key];        if(typeof _proto[key] == "function") {            Object.defineProperty(constructor.prototype,key,{"enumerable":false});        }    }    // 為Class擴充方法/屬性的函數    constructor.extend = function(obj) {        for(var key in obj) {            if(this.hasOwnProperty(key)) {                Error("this property already exist");            } else {                this.prototype[key] = obj[key];                if(typeof obj[key] == "function") {                    Object.defineProperty(this.prototype,key,{"enumerable":false});                }            }        }    }    // 為Class刪除方法/屬性的函數    constructor.delete = function(array) {        array.forEach(function(item){            delete this.prototype[item];        });    }    // 為Class重寫方法/屬性的函數    constructor.rewrite = function(key,value) {        this.prototype[key] = value;        if(typeof this.prototype[key] == "function") {            Object.defineProperty(this.prototype,key,{"enumerable":false});        }    }}// 聲明一個類,如果有基類superType,則產生其子類function Class(name,constructor,_proto,superType){    // 適配瀏覽器和非瀏覽器(nodejs等)    var Global = Global || window;        if(superType) {            // 建立一個Class並進行初始化和父類初始化(組合繼承:原型鏈繼承+借用建構函式)        Global[name] = function (obj) {            var arg = obj ? obj : {};            superType.call(this,arg);            constructor.call(this,arg);        };        Global[name].name = name;        Object.defineProperty(Global[name],"name",{"value":name,"enumerable":false,"writable":false});                // 寄生繼承        var pro = Object.create(superType.prototype);        pro["constructor"] = Global[name];        Global[name].prototype = pro;        // 使建構函式不可被for-in遍曆,排除幹擾        Object.defineProperty(Global[name].prototype,"constructor",{"enumerable":false});                // 初始化prototype和靜態方法        initClass(Global[name],_proto);        } else {                // 建立一個Class        Global[name] = constructor;        Object.defineProperty(Global[name],"name",{"value":name,"enumerable":false,"writable":false});        // 初始化prototype和靜態方法        initClass(Global[name],_proto);    }}

 

測試代碼如下:

Class("Person",function (obj){    obj.name ? this.name = obj.name : obj.name ;},{    "name":"Unnamed",    "gender":"Male",    "sayHello":function(){        console.log(this.name + ":Hello");    }});Class("PersonWithAge",function(obj){    obj.age ? this.age = obj.age : obj.age;},{    "age":"1",    "sayGoodbye":function(){        console.log(this.name + ":Goodbye");    }},Person);Class("PersonMaria",function(obj){    // obj.age ? this.age = obj.age : obj.age;},{    "name":"Maria",    "sayGoodbye":function(){        console.log(this.name + ":Goodbye");    }},Person);Class("PersonMariaWithAge",function(obj){    obj.age ? this.age = obj.age : obj.age;},{    "name":"Maria",    "age":"1",    "sayGoodbye":function(){        console.log(this.name + ":Goodbye");    }},Person);var jack = new Person({"name":"Jack"});var potterWithAge = new PersonWithAge({"name":"Potter","age":"18"});var maria = new PersonMaria();var mariaWithAge = new PersonMariaWithAge({"age":"16"});console.log(jack);//console.log(jack.constructor);console.log(jack instanceof Person);console.log(potterWithAge);//console.log(potterWithAge.constructor);console.log(potterWithAge instanceof Person);console.log(potterWithAge instanceof PersonWithAge);console.log(maria);//console.log(maria.constructor);console.log(maria instanceof Person);console.log(maria instanceof PersonMaria);console.log(mariaWithAge);//console.log(mariaWithAge.constructor);console.log(mariaWithAge instanceof Person);console.log(mariaWithAge instanceof PersonMariaWithAge);Class("PersonWithAgeAndHeight",function(obj){    obj.height ? this.height = obj.height : obj.height;},{    "height":"180",    "sayHeight":function(){        console.log(this.name + ":Height is " + this.height);    }},PersonWithAge);var johnWithAgeAndHeight = new PersonWithAgeAndHeight({"name":"John","height":"160"});console.log(johnWithAgeAndHeight);console.log(johnWithAgeAndHeight instanceof Person);console.log(johnWithAgeAndHeight instanceof PersonWithAge);console.log(johnWithAgeAndHeight instanceof PersonWithAgeAndHeight);function getInfo(obj){var str = "<br>{<br>";for(key in obj) {str += "&nbsp;&nbsp;" + key + ‘:"‘ + obj[key] + ‘",<br>‘};str.slice(0,-5);str+="}";return str;}document.write(getInfo(jack) + "<br>");//console.log(jack.constructor);document.write("jack instanceof Person&nbsp;:&nbsp;" + (jack instanceof Person) + "<br>");document.write(getInfo(potterWithAge) + "<br>");//console.log(potterWithAge.constructor);document.write("potterWithAge instanceof Person&nbsp;:&nbsp;" + (potterWithAge instanceof Person) + "<br>");document.write("potterWithAge instanceof PersonWithAge&nbsp;:&nbsp;" + (potterWithAge instanceof PersonWithAge) + "<br>");document.write(getInfo(maria) + "<br>");//console.log(maria.constructor);document.write("maria instanceof Person&nbsp;:&nbsp;" + (maria instanceof Person) + "<br>");document.write("maria instanceof PersonMaria&nbsp;:&nbsp;" + (maria instanceof PersonMaria) + "<br>");document.write(getInfo(mariaWithAge) + "<br>");//console.log(mariaWithAge.constructor);document.write("mariaWithAge instanceof Person&nbsp;:&nbsp;" + (mariaWithAge instanceof Person) + "<br>");document.write("mariaWithAge instanceof PersonMariaWithAge&nbsp;:&nbsp;" + (mariaWithAge instanceof PersonMariaWithAge) + "<br>");document.write(getInfo(johnWithAgeAndHeight) + "<br>");document.write("johnWithAgeAndHeight instanceof Person&nbsp;:&nbsp;" + (johnWithAgeAndHeight instanceof Person) + "<br>");document.write("johnWithAgeAndHeight instanceof PersonWithAge&nbsp;:&nbsp;" + (johnWithAgeAndHeight instanceof PersonWithAge) + "<br>");document.write("johnWithAgeAndHeight instanceof PersonWithAgeAndHeight&nbsp;:&nbsp;" + (johnWithAgeAndHeight instanceof PersonWithAgeAndHeight) + "<br>");document.write("johnWithAgeAndHeight instanceof PersonMaria&nbsp;:&nbsp;" + (johnWithAgeAndHeight instanceof PersonMaria) + "<br>");

 

測試結果如下(瀏覽器視窗輸出):

{  name:"Jack",  gender:"Male",}jack instanceof Person : true{  name:"Potter",  age:"18",  gender:"Male",}potterWithAge instanceof Person : truepotterWithAge instanceof PersonWithAge : true{  name:"Maria",  gender:"Male",}maria instanceof Person : truemaria instanceof PersonMaria : true{  age:"16",  name:"Maria",  gender:"Male",}mariaWithAge instanceof Person : truemariaWithAge instanceof PersonMariaWithAge : true{  name:"John",  height:"160",  age:"1",  gender:"Male",}johnWithAgeAndHeight instanceof Person : truejohnWithAgeAndHeight instanceof PersonWithAge : truejohnWithAgeAndHeight instanceof PersonWithAgeAndHeight : truejohnWithAgeAndHeight instanceof PersonMaria : false

 

一種基於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.