class类:
es6之前js用构造函数的方式来进行对象的创建,其他语言都具有类这个概念以及对应的类型
es6之后 引入class 类
// es6之前构造函数定义
function People(name, age) { //构造函数 类
this.name = name
this.age = age
}
People.prototype.showInfo = function () {
console.log(this.name);
}
var s1 = new People("王一", 21)
var s2 = new People("王二", 22)
console.log(s1.showInfo == s2.showInfo); //true
// es6之后
class People {
constructor(name, age) { //构造函数,所有的属性写在里面
this.name = name
this.age = age
}
showInfo() { //shoInfo方法
console.log(this.name);
}
}
let p1 = new People("王一", 21)
let p2 = new People("王二", 22)
console.log(p1.showInfo == p2.showInfo); //true
继承:
class People {
constructor(name, age) { //构造函数,所有的属性写在里面
this.name = name
this.age = age
}
showInfo() { //shoInfo方法
console.log(this.name);
}
}
// 继承 创建一个学生类 继承人类
// A extends B => A继承B
// super父级的原型
class Student extends People {
constructor(name, age, score) {
super(name, age) //super方法调用的是它父级的构造函数的属性
this.score = score
}
}
let s1 = new Student("王一", 21, 80)
console.log(s1); //{name: "王一", age: 21, score: 80}
s1.showInfo() //王一 People类的方法也会被继承过来
覆盖:
class People {
showInfo() { //shoInfo方法
console.log(123);
}
}
class Student extends People {
showInfo() { //子级的方法覆盖父级
console.log("abc");
}
}
let s1 = new Student()
s1.showInfo() //abc