class基本
es5>>>
const Hongtao = function(a,b){
this.a = a;
this.b = b;
return this;
}
Hongtao.prototype = {
constructor : Hongtao,
print : function(){
console.log(this.a+' '+this.b);
}
}
const hongtao = new Hongta('hello','world').print();
es6中>>>
class Hongtao{
constructor(a,b){
this.a = a;
this.b = b;
}
print(){
console.log(this.a + ' ' + this.b);
}
}
console.log( new Hongtao('hello','world').print() );
class继承
三个关键子字 : extends/static/super
- extends
es5中的继承
//定义一个继承函数
class Parent{
constructor(name,age){
this.name = name;
this.age = age;
}
getAge(){
return this.age;
}
}
class Sun extends Parent{
constructor(name,age){
super(name.age);//需要注意,相当于继承了父类的构造函数中的属性,想继承哪个属性就传哪个参数
}
getAge2(){
return (this.age + 31);
}
}
class Sun2 extends Sun{
constructor(name,age){
super(name,age);//需要注意,相当于继承了父类的构造函数中的属性,想继承哪个属性就传哪个参数
}
}
console.log( new Sun('hongtao',21).getAge() )
console.log( new Sun2('hongtao',21).getAge2() )
console.log( new Sun2('hongtao',21).getAge() )
- static
类相当于实例的原型, 所有在类中定义的方法, 都会被实例继承。 如果在一个方法前, 加上static关键字, 就表示该方法不会被实例继承, 而是直接通过类来调用, 这就称为“ 静态方法”。
class Parent{
constructor(name,age){
this.name = name;
this.age = age;
}
static getAge(obj){
return obj.age;
}
}
var hong = new Parent('hongtao',21);
console.log( hong.getAge() )//找不到这个方法
console.log( Parent.getAge(hong) )//21
- super
ES6中super用于类继承,有二种方式:
直接作函数使用,但只能用在构造函数中;
作为父类,可调用父类的方法和属性(包括静态)
class Parent{
constructor(name,age){
this.name = name;
this.age = age;
}
static getAge(){
return this.age;
}
}
class Sun extends Parent{
constructor(name,age){
super(name,age);
this.getAge = Sun.getAge;//构造函数内使用了super,子类会继承父类的静态方法,但只限于构造函数内
}
getAge2(){
return (this.age + 31);
}
}
PS : 本人也是新手,如有技术问题,请联系QQ : 836717428