• 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
    
  • 相关阅读:
    C#中的语言记忆功能
    C#中 文件的打开及保存
    无边框窗体设置
    Windows获取浏览器中存储的明文密码
    (CVE-2020-17530)Struts2 S2-061漏洞复现
    (CVE-2020-14882​&14883)Weblogic RCE复现
    内网渗透学习-信息收集篇
    Spring Boot Actuator H2 RCE复现
    Linux解压文件
    Windows本地提权
  • 原文地址:https://www.cnblogs.com/Jyc403/p/15522684.html
Copyright © 2020-2023  润新知