面向对象:
- 声明一个类: 关键字 class 类名{ }
类名命名规范:首字母大写 不能用中文和数字以及关键字 -
- 通过class定义类,实现类的继承
- 在类中通过constructor定义构造方法 魔术方法 实例化的时候 自动调用
- 通过new来创建类的实例
- 通过extends(继承)来实现类的继承来实现类的继承
- 通过super调用父类的构造方法
- 重写从父类中继承的一般方法
- 类里面有成员属性 和 成员方法
- 子类通过构造方法新增新的内容,必须先要super调用父类的构造方法
基本用法:
<script>
class Stus {
// 定义构造方法 当类实例化时自动会触发构造方法
constructor(name,age){ // 通过constructor定义构造方法
console.log('构造方法'); // 构造方法
this.name = name;
this.age = age;
}
// 定义一般的方法 类的成员方法
silp(){
console.log(this.name,this.age); // 小明 20
};
show(){
console.log('学习') // 学习
};
}
let s = new Stus('小明',20) // 实例化得到Stus这个类 严格区分大小写
s.silp();
s.show();
</script>
继承:extends
子类继承了父类 就拥有了父类构造方法,但是子类里面要在构造方法中新增的内容,则必须先用super调用父类的构造方法,继承了父类 拥有了父类的方法 在子类重新定义方法(重写或覆盖)
<script>
class Father{
constructor(name,age){
this.name = name;
this.age = age;
}
// 定义方法
dis(){
console.log(this.name,this.age);
}
}
class Son extends Father{ // 通过extends(继承)来实现类的继承来实现类的继承
// 定义构造方法
constructor(name,age,city){ // 通过constructor定义构造方法
super(name,age); // 通过super调用父类的构造方法
this.city = city;
}
// // 重写 覆盖
// dis(){
// console.log(this.city); // 北京
// }
dis(){
console.log(this.name,this.age,this.city); // dfgj 18 北京
}
}
let s = new Son('dfgj',18,'北京');
s.dis();
</script>