ES6-extends

来源:互联网 发布:安卓看图软件 编辑:程序博客网 时间:2024/06/05 09:18
extends继承,ColorPoint 子类,Point 父类


1.super关键字,它在这里表示父类的构造函数,用来新建父类的this对象。
3.super这个关键字,既可以当作函数使用,也可以当作对象使用。在这两种情况下,它的用法完全不同

4.第一种情况,super作为函数调用时,代表父类的构造函数

5.super作为对象时,指向父类的原型对象。



class Point{    constructor(x, y) {      this.x = x;      this.y = y;    }  }  Object.assign(Point.prototype, {    toString(){      return this.x+this.y;      },    toValue(){}  });class ColorPoint extends Point {  constructor(x, y, color) {    super(x, y); // 调用父类的constructor(x, y),    this.color = color;  }  toString() {    return this.color + ' ' + super.toString(); // 调用父类的toString()  }}let cPoint = new ColorPoint(3,3,"red");console.log(cPoint);


class A {  constructor(x){    this.x = 1;  };  p() {    return 2;  }}class B extends A {  constructor(x) {     super();     this.x = 2;     super.x = 3;    console.log(this.x); // 2    console.log(super.x); // undefined    console.log(A.prototype.x);    // super.x赋值为3,这时等同于对this.x赋值为3。而当读取super.x的时候,读的是A.prototype.x,所以返回undefined。  }}let b = new B();let a = new A();console.log(a.x);




原创粉丝点击