(1)class的基本语法
声明类:
class Person{
};
let p=new Person()
console.log(p);//Person {}
匿名类:
let fn=class{
}
let fn1=new fn()
console.log(fn1);//fn {}
类的数据类型就是函数,类本身就指向构造函数:
//类的语法,建议大写
class Person{
};
console.log(typeof Person);//function
直接对类使用new命令,跟构造函数的用法完全一致:
class person{
fn(){
console.log("你好");
}
};
let str=new person();
str.fn();//你好
构造函数的prototype属性,在 ES6 的“类”上面继续存在。事实上,类的所有方法都定义在类的prototype属性上面
class Point {
constructor() {
// ...
}
toString() {
// ...
}
toValue() {
// ...
}
}
// 等同于
Point.prototype = {
constructor() {},
toString() {},
toValue() {},
};
constructor()方法
constructor()方法是类的默认方法,通过new命令生成对象实例时,自动调用该方法。一个类必须有constructor()方法,如果没有显式定义,一个空的constructor()方法会被默认添加。
class Point {
}
// 等同于
class Point {
constructor() {}
}
类的继承
- 解决代码的复用
- 使用extends关键字实现继承
- 子类可以继承父类中所有的方法和属性
- 子类只能继承一个父类(单继承),一个父类可以有多个子类
- 子类的构造方法中必须有super()来指定调用父类的构造方法,并且位于子类构造方法中的第一行
- 子类中如果有与父类相同的方法和属性,将会优先使用子类的(覆盖)
class People {
//父类构造方法
constructor() {
this.a = 100; //父类中定义的变量
console.log("People constructor");
}
//原型方法
eat() {
console.log("eat...")
}
//静态方法
static play() {
console.log("play...")
}
}
//继承
class Student extends People {
//子类构造方法
constructor() {
super(); //调用父类构造器,必须存在,且位于子类构造器第一行的位置
this.b = 200; //子类定义的变量
console.log("Student constructor");
}
study() {
console.log("study...");
}
}
let stu = new Student();
console.log(stu.a, stu.b);
stu.eat();
stu.study();
Student.play();