1,首先子类继承父类的方法
// 调用父类的函数,super必须要要写到子类this的前面
<script>
// 新建一个父类
class Father {
constructor(x , y){
this.x = x ;
this.y = y ;
}
sunm( ){
console.log(this. x + this.y) ;
}
}
// 子类继承
class Son extends Father {
constructor(x , y){
// 调用父类的函数,super必须要要写到子类this的前面
super(x ,y) ;
//这个this 是子类的
this.x = x;
this.y = y;
}
// 子类独有的类.可以扩展自己的方法
sub(){
console.log( this.x - this.y)
}
}
var son = new Son( 5 ,3);
son.sub();
son.sunm ();
</script>
2.ES6 中的类和对象
-
在 ES6 中类没有变量提升,所以必须先定义类,才能通过类实例化对象.
-
类里面的共有属性和方法一定要加this使用.
-
类里面的this指向问题.
-
constructor 里面的this指向实例对象, 方法里面的this 指向这个方法的调用者