详解super()函数

详解super()函数

super()函数用于访问和调用一个对象上的父对象上的函数。

前言

super.prop 和 super[expr]表达式在类和对象字面量任何方法定义中都是有效的。

一、语法?

super([arguments])
//调用 父对象/父类 的构造函数
super.functionOnParent([arguments]);
//调用 父对象/父类 上的方法

二、描述

在构造函数中使用时,super关键字将单独出现,并且必须在使用this关键字之前使用。
super关键字也可以调用父对象上的函数。

三、示例

1:在类中使用super

    class Polygon {
        constructor(height, width) {
            this.name = 'Rectangle';
            this.height = height;
            this.width = width;
        }
        sayName() {
            console.log('Hi, I am a ', this.name + '.');
        }
        get area() {
            return this.height * this.width;
        }
        set area(value) {
            this._area = value;
        }
    }

    class Square extends Polygon {
        constructor(length) {
            this.height; // ReferenceError,super 需要先被调用!

            // 这里,它调用父类的构造函数的,
            // 作为Polygon 的 height, width
            super(length, length);

            // 注意: 在派生的类中, 在你可以使用'this'之前, 必须先调用super()。
            // 忽略这, 这将导致引用错误。
            this.name = 'Square';
        }
    }
    let p = new Polygon(10,20);
    p.sayName();

神鼎飞丹砂
我们可以看到constructor中this指向这个实例,添加了height和name,width两个属性;并在它的原型对象上添加了sayName,get area方法;
在这里插入图片描述
调用super()函数,继承了父级函数的height和width;

2:调用父类上的静态方法

    class Rectangle {
        constructor() {}
        static logNbSides() {
            return 'I have 4 sides';
        }
    }

    class Square extends Rectangle {
        constructor() {
            super();
/**1.在通过new关键字创建对象时,会通过构造函数return一个实例对象。
2.此时若父类和子类均含有构造函数,则根据就近原则,会直接调用子类的构造函数。
此时就会报错了,因为根据继承的原则,在子类构造函数返回前,必须调用super父类构造函数。**/
        }
        static logDescription() {
            console.log(super.logNbSides() + ' which are all equal');
        }
    }
    let s = new Square();
    Square.logDescription(); // 'I have 4 sides which are all equal'

在这里插入图片描述

3:删除 super 上的属性将抛出异常

class X {
  constructor() {
    Object.defineProperty(this, 'prop', {
      configurable: true,
      writable: false, 
      value: 1
    });
  }
}

class Y extends X {
  constructor() {
    super();
  }
  foo() {
    super.prop = 2;   // Cannot overwrite the value.
  }
}

var y = new Y();
y.foo(); // TypeError: "prop" is read-only
console.log(y.prop); // 1

4:在对象字面量中使用super.prop

var obj1 = {
  method1() {
    console.log("method 1");
  }
}

var obj2 = {
  method2() {
   super.method1();
  }
}

Object.setPrototypeOf(obj2, obj1);
obj2.method2(); // logs "method 1"
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值