ES6 的类继承时,在子类的 constructor 函数中以 super 方法执行来指定 this
class Parent{constructor(name = 'zhangsan'){this.name = name;}say(){console.log(1);}static a(){ // 静态方法无法继承console.log(2);}}// 派生类class Child extends Parent{constructor(name = 'lisi', age = 19){super(name); //在constructor 以 super 函数执行来指定 thisthis.age = age;this.type = 'child';}}console.log(new Child().say());
super 当对象时候
- 在对象当中指代对象的原型 ```javascript let proto = { y: 20, z: 40 }
let obj = { x: 10, foo: super.y, // 报错 不能用于属性 foo: function() { // 报错 console.log(super.y); }, foo: () => { // 报错 console.log(super.y); }, foo() { // 只能用对象方法简写的方法中 console.log(super.y); // 20 } };
2. 在静态方法,指向自己的父类```javascriptclass Parent {static myMethod(msg) {console.log('static', msg);}myMethod(msg) {console.log('instance', msg);}}class Child extends Parent {static myMethod(msg) {super.myMethod(msg); // super 指向父类因此访问的是static myMethod}myMethod(msg) {super.myMethod(msg); // super 指向的是父类的构造函数, 访问的是 Parent.prototype.myMethod}}Child.myMethod(222); // static 222let child = new Child();child.myMethod(111); // instance 111
