class语法是es6新加的语法,用于生成一个类,es5时生成类是通过构造函数,看着特别不舒服。
es5声明类:
// function Point(x,y) { // this.x=x; // this.y=y; // } // // Point.prototype.toString=function () { // return '('+this.x+','+this.y+')' // };
class声明一个同样的类:
// class pointClass{ // constructor(x,y){ // this.x=x; // this.y=y; // } // // toString(){ // return '('+this.x+','+this.y+')' // } // }
class里面还有静态方法只有这个类自己可以调用,只需要在方法面前加一个static
(只有静态方法没有静态实例)
class A{
construcor(){
}
static staticFuc(){
console.log("static_fuc");
}
}
A.staicFuc();//static_fuc
class 中的set 和get:用于拦截实例的变化
class my_class{
constroctor(){
this.props=1;
}
set props(value){
console.log(value);
}
get props(){
console.log("getter);
}
}
let inst=new my_class();
inst.props=123;//123
inst.props//getter
类的继承:子类会继承父类的方法和变量
class Foo{ static fa_method(){ return "hello" } } class Bar extends Foo{ }console.log(Bar.fa_method());
super的用法:它既可以当函数使用亦可以当对象使用
(1)super作为函数调用时代父类的构造函数,且子类的构造函数必须执行一次super
即有构造函数就必须执行super//否则会报错
class A{}
class B extend A{
constructor(){
super()
}
}
(2) super作为对象时普通方法中指向父类的原型对象,静态方法中指向父类
也就是说当对象使用时子类中可以利用super调用父类的方法
class A{
p(){
}
}
class B extends A{
constructor(){
super()
console.log(super.p());
}
}
注意:父类方法中的this指向子类