class Animal { constructor(){ this.type = 'animal'; } speak(){ console.log(this.type); } }
至关于下面ES5的这样的写法函数
function Animal(){ this.type = 'animal'; } Animal.prototype.speak = function(){ console.log(this.type); }
class Animal { constructor(){ this.type = 'animal'; } speak(){ console.log(this.type); } } class Cat extends Animal { constructor(){ super(); this.type = 'cat' } }
至关于下面ES5的写法this
function Animal(){ this.type = 'animal'; } Animal.prototype.speak = function(){ console.log(this.type); } function Cat(){ Animal.call(this); this.type = 'animal'; } Cat.prototype = Object.create(Animal.prototype); Cat.prototype.constructor = Cat;//由于上一步形成constructor为Animal //或者能够把上边的两行改为下面这样的写法 Cat.prototype = Object.create(Animal.prototype, { constructor: Cat, });
从上边的例子可能已经领略了super的一些用法了。可是还不全面。super在类的继承中,有两个用法prototype
在类的继承中,子类若是显式的声明了构造函数,则必须首先调用super,否则会找不到this。此时super表明父类的构造函数。这时在构造函数里调用super(),至关于 parentConstructor.call(this). 仍是以上边的实际例子为例。code
class Cat extends Animal { constructor(){ super(); // 至关于 Animal.call(this) this.type = 'cat' } }
如今再解释一个疑问。若是在继承中子类压根不写构造函数呢?不过不写,至关于也写了。只是构造函数用的是父类的构造函数对象
class Cat extends Animal { } // 至关于 class Cat extends Animal { constructor(...args){ super(...args); } }
super做为对象时,在普通方法中,指向父类的原型对象;在静态方法中,指向父类。继承
在普通方法中,指向父类的原型对象,下面举例原型
class Animal { constructor(){ this.type = 'animal'; } } Animal.prototype.type ="type on propotype" class Cat extends Animal { constructor(){ super(); this.type = 'cat' console.log(super.type) } } new Cat(); // 此处打印出来的是type on propotype,而不是animal
在静态方法中指向父类io
class Animal { static type = 'this is static type'; constructor(){ this.type = 'animal'; } } Animal.prototype.type ="type on propotype" class Cat extends Animal { constructor(){ super(); this.type = 'cat' } static miao(){ console.log(super.type); // 这里输出的是this is static type,而不是animal或者type on propotype } } Cat.miao()