zoukankan      html  css  js  c++  java
  • JS中常见的几种继承方式

    JS的三种继承方式

    1.ES6 类继承
    		//1- es6 类继承
            class Parent {
                constructor() {
                    this.age = 30;
                }
            }
            class Child extends Parent {
                constructor() {
                    super();
                    this.name = '张三';
                }
            }
            let o1 = new Child();
            console.log(o1, o1.name, o1.age);// Child {age: 30, name: '张三'} '张三' 30
    
    2.原型链继承

    ​ 优点: 父类方法可以复用

    ​ 缺点:父类的所有引用属性(info)会被所有子类共享,更改一个子类的引用属性,其他子类也会受影响子类型实例不能给父类型构造函数传参

    		// 2- 原型链继承
            function Parent() {
                this.age = 30;
            }
            function Child() {
                this.name = '张三';
            }
            Child.prototype = new Parent();
            let o2 = new Child();
            console.log(o2, o2.name, o2.age);// Child {name: '张三'} '张三' 30
    
    3.构造函数继承

    ​ 优点: 1.可以在子类构造函数中向父类传参数

    ​ 2.父类的引用属性不会被共享

    ​ 缺点:只能继承构造函数的内部成员,不能继承原型链(Parent.prototype)上的方法

    		// 3- 构造函数继承
            function Parent() {
                this.age = 18;
            }
            function Child() {
                this.name = '张三';
                Parent.call(this);
            }
            let o3 = new Child();
            console.log(o3, o3.name, o3.age);// Child {name: '张三', age: 18} '张三' 18
    
    4.混合继承

    ​ 优点: 1.父类的方法可以复用

    ​ 2.可以在Child构造函数中向Parent构造函数中传参

    ​ 3.父类构造函数中的引用属性不会被共享

    		// 4- 组合式继承
            function Parent() {
                this.age = 19;
            }
            function Child() {
                Parent.call(this);
                this.name = '张三';
            }
            Child.prototype = new Parent();
            let o4 = new Child();
            console.log(o4, o4.name, o4.age);// Child {age: 19, name: '张三'} '张三' 19
    
  • 相关阅读:
    Namenode主节点停止报错 Error: flush failed for required journal
    IntelliJ IDEA2018.3 最新破解方法
    idea 中解决maven 包冲突的问题(maven helper)
    java中的守护线程
    synchronized锁住的是代码还是对象
    maven package,clean,install,compile命令
    设计模式——装饰者模式
    设计模式——观察者模式
    com.alibaba.fastjson.JSON对类对象的序列化与反序列化
    java8 Stream使用案例
  • 原文地址:https://www.cnblogs.com/Jyc403/p/15522684.html
Copyright © 2011-2022 走看看