类和继承
1.类
class Person {
constructor(uname, age) {
this.uname = uname
this.age = age
}
eat() {
console.log('吃');
}
}
let zs = new Person('张三', 18)
zs.eat()
1.本质:类在本质上就是构造函数的新写法
2.作用:用来创建对象
3. 使用:
class 类名 {
constructor(形参,形参...) {
this.形参 = 形参
this.形参 = 形参
...
}
函数名() {
}
}
4. 注意:
1)类的属性必须通过constructor设置
2)类中方法的设置在constructor外部添加一个函数,函数不能有function
3)类中的方法默认添加到prototype上
4)通过类创建对象时,程序会默认执行constructor中代码
5)类名遵守帕斯卡命名法
6)类中的方法和属性相互访问要加上this
this.属性
this.方法()
2.继承
class Person {
constructor(uname, age, gender) {
this.uname = uname
this.age = age
this.gender = gender
}
eat() {
console.log('吃');
}
}
class Student extends Person {
constructor(uname, age, gender, score) {
super(uname, age, gender)
this.score = score
}
test() {
console.log(this.uname + '考试' + this.score + '分');
this.aword()
}
aword() {
console.log('爸爸奖励了' + this.uname + '100元');
}
punish() {
console.log('爸爸奖励了一耳光');
}
eat() {
console.log('吃苹果');
}
}
let zs = new Student('张三', 18, '男', 150)
zs.test()
zs.eat()
1) 继承语法
class 子类 extends 父类 {
constructor() {
super()
}
}
2) 父类中的形参通过super传送, constructor要填入所有参数
3) 子类的方法可以和父类方法同名, 覆盖父类的方法
4) 类中的属性和方法相互访问要加上this