zoukankan      html  css  js  c++  java
  • js继承

    组合式继承

    function super(name){
        this.name=name;
        this.colors=["red","blue","green"]
    }
    super.prototype.sayName=function(){
        console.log(this.name);
    };
    
    function sub(name,number){
        // 继承属性
        super.call(this,name);
        this.number=number;
    }
    //继承方法
    sub.prototype=new super();//类似继承,引用,子类改变会影响父类
    sub.prototype.sayNum=function(){
        console.log(this.number);
    }
    
    var instance1=new sub("cherry",23);
    instance1.colors.push("magenta");
    console.log(instance1.colors);//"red,blue,green,magenta"
    instance1.sayName();//"cherry"
    instance1.sayNum();//23
    
    var instance2=new sub("blueberry",25);
    console.log(instance2.colors);//"red blue,green"
    instance2.sayName();//"blueberry"
    instance2.sayNum();//25
    
    //融合了原型链和构造函数的优点

     寄生组合式继承

    function super(name){
        this.name=name;
        this.colors=["red","blue","green"];
    }
    
    super.prototype.sayName=function(){
        console.log(this.name);
    }
    
    function sub(name,age){
        super.call(this,name);
        this.age=age;
    }
    
    //
    function inheritPrototype(sub,super){
        var prototype=object(super);//创建super原型的一个副本
        prototype.constructor=sub;//为创建的副本添加constructor属性
        //从而弥补因原型重写而失去的默认的constructor属性
        sub.prototype=prototype;//将创建的副本赋值给子类原型
        //即可调用inheritPrototype()替换组合继承中为子类原型赋值的语句
    }
    inheritPrototype(sub,super);
    
    sub.prototype.sayAge=function(){
        console.log(this.age);
    }

    原型链继承即将一个对象的实例赋值给另一对象的原型实现继承

    拷贝继承

     修复类似继承:借助中间类实现

        var a={
                    name:'roy'
                }
                var b=cloneobj(a);
                
                b.name='richard';
                alert(a.name);
                alert(b.name);
                function cloneobj(obj){//原型继承
                    var f=function(){};//中间子类
                    f.prototype=obj;
                    return new f();
                }
                
                
                //拷贝继承:比较通用的方式,有无new都可以用
                //类式继承:new 构造函数
                //原型继承:无new对象
  • 相关阅读:
    关于hexo-abbrlink链接undefined
    如何修改layer-layui中的confirm
    cmder的segmentation fault错误修复
    论好的代码习惯的养成/做一个优雅的coder
    50行代码写的一个插件,破解一个H5小游戏
    慎用array_filter函数
    python:if 语句的使用方法
    python:for语句的使用方法
    关于python3 发送邮件
    zookpeer的安装与配置
  • 原文地址:https://www.cnblogs.com/rlann/p/6591582.html
Copyright © 2011-2022 走看看