zoukankan      html  css  js  c++  java
  • (2)基于原型的类继承

    1 version 1

    var Animal = function(){
            this.init(this,arguments);
        };
    
        //init
        Animal.prototype.init = function(color){
            this.color = color;
        };
        Animal.prototype.breath = function(){
            console.log("breath");
        };
    
        var Dog = function(){};
        Dog.prototype = new Animal();
    
        Dog.prototype.init("white");
    
        Dog.prototype.getColor = function(){
            console.log(this.color);
        };
    
        var dog = new Dog();
        dog.breath();//breath
        dog.getColor();//white

    (1) Dog类继承Animal类,这种继承属于原型继承,那就是说Dog的原型里面拥有Animal类的实例

    2 version 2 类库添加继承

    var Class = function(parent){
            var klass = function(){
                this.init.apply(this,arguments);
            };
            if(parent){
                var subClass = function(){};
                subClass.prototype = parent.prototype;
                klass.prototype = new subClass();
            }
            //init
            klass.prototype.init = function(){};
            klass.fn = klass.prototype;
            klass.fn.parent = klass;
            //add class property
            klass.extend = function(obj){
                var extended = obj.extended;
                for(var i in obj){
                    klass[i] = obj[i];
                }
                if(extended) extended(klass);
            };
            //add prototype property
            klass.include = function(obj){
                var included = obj.included;
                for(var i in obj){
                    klass.fn[i] = obj[i];
                }
                if(included) included(klass);
            };
            return klass;
        };
    
        var Animal = new Class();
    
        Animal.include({
            breath:function(){
                console.log('breath');
            }
        });
    
        var Cat = new Class(Animal);
        var tommy = new Cat();
        tommy.breath();


    可以仔细看这段代码

     if(parent){
                var subClass = function(){};
                subClass.prototype = parent.prototype;
                klass.prototype = new subClass();
            }

    再次将Animal这个function传回去,新建一个局部的subClass的原型指向Animal的原型,再将klass的原型指向subClass的实例,防止了原型污染

  • 相关阅读:
    MySQL DELAY_KEY_WRITE Option
    More on understanding sort_buffer_size
    myisam_sort_buffer_size vs sort_buffer_size
    share-Nothing原理
    GROUP_CONCAT(expr)
    Mysql History list length 值太大引起的问题
    Why is the ibdata1 file continuously growing in MySQL?
    洛谷1201 贪婪的送礼者 解题报告
    洛谷1303 A*B Problem 解题报告
    洛谷2142 高精度减法 解题报告
  • 原文地址:https://www.cnblogs.com/lihaozhou/p/3965192.html
Copyright © 2011-2022 走看看