zoukankan      html  css  js  c++  java
  • 浅谈ES5和ES6继承和区别

    最近想在重新学下ES6,所以就把自己学到的,记录下加强下自己的理解

    首先先简单的聊下ES5和ES6中的继承

    1.在es5中的继承:

    function parent(a,b){
        this a = a;
        this b = b;
    }
    function child(c){
        this c = c
    };

      通过子集去继承父级:

    parent.call(child,1,2)

      而去看call的底层方法可知,继承的过程是通过prototype属性

    child.prototype = new parent(1,2);

      又此可知,ES5继承的实质是先创建了子类元素child的的实例对象,然后再把父类元素parent的原型对象中的属性赋值给子类元素child的实例对象里面,从而实现继承

    2.ES6中的继承

      在传统JS中,生成对象是通过创建构造函数,然后定义生成对象

    function parent(a,b){
        this.a = a;
        this.b = b;
    }

      然后通过prototype增加对应所需方法或属性

    parent.prototype.methods = function(){
        return 'this is test methods';
    }
    parent.prototype.attr = 'this is test attr‘;

      而ES6中引入了类的概念,也就是class。通过关键词class去定义对象。
      class是个关键词,语言糖,这样能更清晰的读懂所创建的对象,
      通过属性constructor来接收控制方法传入的参数,如果不写这个属性,默认是没有参数的

    class parent{
        curstructor(a,b){
            this.a = a;
            this.b = b;
        }
    }        

      ES6中的继承是基于class类之间继承的。通过关键词extends实现。
      通过super实例化调用父类

    class parent{
      constructor(a,b){
        this.a = a;
        this.b = b;
      }
      parentMethods(){
        return this.a + this.b
      }
    }
    class child extends parent{
      constructor(a,b,c){
        super(a,b);
        this.c = c;
      }
      childMethods(){
        return this.c + ',' + super.parentMethods()
      }
    }
    const point = new child(1,2,3);
    alert(point.childMethods());

      上面的代码,是一套简单的ES6父子类继承。
      相信已经看出来了,虽明显的区别就是在于ES6中,激活父组件的是super方法,而不是新建实例化,也就是说,父类的实例对象是先创建出来的,调用后,再去修改子类的构造函数中的this完善原型对象

    总结:

      ES5和ES6继承最大的区别就是在于:
        1.ES5先创建子类,在实例化父类并添加到子类this中
        2.ES6先创建父类,在实例化子集中通过调用super方法访问父级后,在通过修改this实现继承

  • 相关阅读:
    Java 8新特性探究(九)跟OOM:Permgen说再见吧
    Java 堆内存(Heap)[转]
    hashmap源码
    Java8学习笔记----Lambda表达式 (转)
    双重检查锁定与延迟初始化(转自infoq)
    kvm的live-snapshot
    8.25考试总结
    CF1151FSonya and Informatics
    CF1151div2(Round 553)
    BZOJ3728 PA2014Final Zarowki
  • 原文地址:https://www.cnblogs.com/wymbk/p/9290232.html
Copyright © 2011-2022 走看看