1.classsegmentfault
class 熟悉的关键字 我大学的主修语言是C#,class 做为后端语言定义类的关键字,引入ES6做为语法糖,引入了后端的思想在咱们能够定义类,更直观的实现类的继承。在建立实例对象的时候除了实例化构造函数,还能够实例化定义好的类。constructor :其中 constructor 方法是类的构造函数,是一个默认方法,经过 new 命令建立对象实例时,
自动调用该方法。它还有几个特性这里来一个一个举例分析。后端
第一个:一个类必须有 constructor 方法,若是没有显式定义,一个默认的 consructor 方法会被默认添加。因此即便你没有添加构造函数,也是会有一个默认的构造函数的。函数
class Parent1{ a=1; } class Parent2{ constructor(){ this.a=1; }; } console.log(new Parent1())//{a: 1} console.log(new Parent2())//{a: 1}
也就是说即便你不添加 constructor 构造函数,它默认也会添加一个而且返回当前类的上下文。
第二个:通常 constructor 方法返回当前构造的实例对象 this ,可是也能够指定 constructor 方法返回一个全新的对象,让返回的实例对象不是该类构造的实例对象。this
class Parent1{ constructor(){ this.a=1; }; } class Parent2{ constructor(a){ return a; }; } console.log(new Parent1())//{a: 1}
也就是说 constructor 默认会返回实例对象的this,可是当你为它手动添加返回值时,就改变了它的返回对象。最后总结:也就是实例化类的时候,constructor做为一个构造器 帮忙把当前类的属性实例化返回一个实例对象。
2.extends super
extends继承,是指在声明一个子类时用extends指定想要继承的父类。这从原理上实际上是从父类的原型继承而来。仍是拆分解读继承的特性举例说明:
(1)在子类 constructor 中必须调用 super 方法,由于子类没有本身的 this 对象,而是继承父类的 this 对象。prototype
class Parent{ constructor(){ this.name="parent"; }; getName(){ console.log(this.name) } } class Child extends Parent { constructor(name){ // this.name=name; super(); this.name=name; }; } let child = new Child("child")//当this.name 在super前执行时 报错 Must call super constructor in derived class before accessing 'this let child = new Child("child")//当this.name 在super后执行时 child.getName();// child
解释:由于子类在继承时没有一个建立上下文的过程,super 就表明了父类的构造函数 也就是Parent 的 constructor ,执行父类的构造函数实例化的对象做为子类的实例。也就是是约等于下边这种实现。code
class Parent{ constructor(){ this.name="parent"; }; getName(){ console.log(this.name) } } class Child { constructor(name){ new Parent(); this.name=name; }; }
在这里须要注意super()在constructor中执行时内部的 this 指的是 B,所以 super() 在这里至关于 ```A.prototype.constructor.call(this, props)``。
(2)子类中的属性如过和父属性重复,在读取时优先读取子类里的属性。对象
class Parent{ constructor(){ this.name="parent"; }; getName(){ console.log(this.name) } } class Child extends Parent { constructor(){ super(); }; getName(){ console.log("child") } } let child = new Child(); child.getName();// child
那若是想要调用继承来的方法,可是还要添加进子类的操做呢。继承
class Child extends Parent { constructor(){ super(); }; getName(){ this.name=" from child"; super.getName(); } } let child = new Child(); child.getName();// from child
最后附上文章参考的传送门get