super關鍵字

2018-07-28  本文已影响0人  叹玖

super关键字用于访问和调用一个父对象上的函数。
在构造函数中使用时,super必须放在this之前,否则,会报错。

1.在类中使用super

class Polygon {
    constructor(height, width) {
        this.name = 'Polygon';
        this.height = height;
        this.width = width;
    }
    sayName() {
        console.log('Hi, I am a ', this.name + '.');
    }
}

class Square extends Polygon {
    constructor(length) {
        //this.height;  //this不允許使用在super前
        super(length, length);
        this.name = 'Square';
    }

    get area() {
        return this.height * this.width;
    }

    set area(value) {
        //this.area = value;
        console.log(value);
    }
}

var res = new Square(2);
console.log(res,res.area); //Square { name: 'Square', height: 2, width: 2 } 4
res.sayName(); //Hi, I am a  Square.

2. 调用父类的静态方法

class Human {
    constructor() {}
    static ping() {
        return 'ping';
    }
}

class Computer extends Human {
    constructor() {}
    static pingpong() {
        return super.ping() + ' pong';
    }
}
console.log(Computer.pingpong());  //ping pong

3.不能使用delete操作符删除super上的属性
class Base {
constructor() {}
foo() {}
}
class Derived extends Base {
constructor() {}
delete() {
 delete super.foo;
}
}

new Derived().delete(); 
// ReferenceError: invalid delete involving 'super'.

4.当使用 Object.defineProperty 定义一个属性为不可写时,super将不能重写这个属性的值。

上一篇下一篇

猜你喜欢

热点阅读