zoukankan      html  css  js  c++  java
  • js构造函数的完美继承(欢迎吐槽)

    function Animal(){                   //定义父类
        this.leibie="动物";
    }
    Animal.prototype.test1=[1,2];
    
    function Cat(name,color){            //定义子类
        Animal.call(this);               //继承父类的this变量属性
    //    Animal.apply(this,arguments);  //如果需要子类参数,也可用这条替代上条语句
        this.name=name;
        this.color=color;
    }
    
    function extend(Child,Parent){      //继承父类的prototype属性
        var c = Child.prototype;
        var p = Parent.prototype;
        for (var i in p){
            if(p.hasOwnProperty(i)){
                if(typeof p[i]==="object"){
                    c[i] = (p[i].constructor === Array)?[]:{};
                    deepCopy(c[i],p[i]);         //深拷贝,拷贝复合类型(Array,Object),而并不是简单的把俩个指针指向同一内存地址。 浅拷贝,拷贝基本类型。
                }
                else{
                    c[i] = p[i];
                }
            }
        }
    }
    
    function deepCopy(childObject,parentObject){
        for (var i in parentObject){
            if(parentObject.hasOwnProperty(i)){
                if(typeof parentObject[i]==="object"){
                    childObject[i] = (parentObject[i].constructor === Array)?[]:{};
                    deepCopy(childObject[i],parentObject[i]);
                }
                else{
                    childObject[i] = parentObject[i];
                }
            }
        }
    }
    
    extend(Cat,Animal);       //继承父类的prototype属性
    
    /*继承的时候可以看需求,如果只需继承prototype的属性,那么不需要Animal.call(this),如果只需要继承本地属性,那么不需要extend,来提高效率。如果都要,则都加上。*/
    
    var cat1 = new Cat("Linda","pink");
    var animal1 = new Animal();
    
    cc.log(cat1.test1[0]);     //1
    cc.log(animal1.test1[0]);  //1
    cat1.test1[0]=2;
    cc.log(cat1.test1[0]);     //2
    cc.log(animal1.test1[0]);  //1
    animal1.test1[0]=3;
    cc.log(cat1.test1[0]);     //2
    cc.log(animal1.test1[0]);  //3
  • 相关阅读:
    鼠标拖放div 实现
    layerX offsetX pageX
    960 grid 使用
    960 grid 分析
    WebMatrix安装和使用
    Sass使用教程
    CSS预处理器实践之Sass、Less比较
    node.js 入门教程(beginnder guide
    node.js NPM 使用
    《Head First 设计模式》学习笔记——状态模式
  • 原文地址:https://www.cnblogs.com/rhythm2014/p/3830938.html
Copyright © 2011-2022 走看看