创建类的写法
```
class Point{
construct(x,y){
this.x=x;
this.y=y;
}
method(){
consol.log(this.x+this.y)
}
}
const point = new Point(1,2)
Point.method() //3
```
静态属性与方法
静态属性与静态方法只能通过类来访问,不可以通过实例来进行访问。但是子类可以继承到,继承后,子类也可以动过子类直接调用
关键字 static
继承
继承写法,通过关键字extend来实现
```
class Point{
constructor(x,y){
this.x=x;
this.y=y;
}
method(){
consol.log(this.x+this.y)
}
}
class PointChild extend Point{
constructor(x,y,z){
super(x,y);//通过super来继承父类的x和y属性
this.z = z;
}
method(){
super.method();
console.log(this.z);
}
}
```
为什么:因为super指向的是父类的原型对象而不是实例对象,所以不能通过父类的实例对象来进行访问。
注意的点:判断子类继承父类可以使用方法Object.getPrototypeOf()
举个栗子:
```
Object.getPrototypeOf(PointChild) === Point;
```
不存在变量提升
ES6里面,不论是使用变量或者调用方法,只要事先没有声明,那么就会报错。但是ES5里面存在变量提升,即使提前使用也只是undefined
类的prototype属性
记住3点:
1,子类的proto属性表示构造函数的继承,总是指向父类。
2,子类prototype属性的proto表示方法的继承,总是指向父类的prototype属性。
3,子类实例的proto属性的proto属性指向父类实例的proto属性。
举个栗子:
```
class A{}
class B extend A{}
B.__proto__ === A //true
B.prototype.__proto__ === A.prototype //true
let a = new A();
let b = new B();
b.__proto__.__proto__ === a.__proto__ //true
```
上面的等式可以这样理解:b.proto===B.prototype
a.proto===A。prototype
因为B.prototype.proto === A.prototype
所以上面等式相等。
网友评论