关于类/class
类是一种对象的模板,ES6 的class可以看作只是一个语法糖,它的绝大部分功能,ES5 都可以做到,新的class写法只是让对象原型的写法更加清晰、更像面向对象编程的语法而已。
特点:
面向对象,具备属性与方法
写法:
ES5原型写法:
// ES5写法
// 构造函数==>创建属性
function Person(name,age){
this.name=name;
this.age=age;
/* this.showName=function(){
return `名字为:${this.name},年龄为${this.age}`;
} */
}
Person.prototype.showName=function(){
return `名字为:${this.name},年龄为${this.age}`;
}
let p1=new Person('ES6',3);
console.log(p1.showName());
ES6写法:
// 创建类(构造函数)
class Person{
constructor(name,age) {
console.log(`constructor果然运行了,标题为"${name}",年龄${age}`);
}
}
console.log(typeof Person);
let p=new Person('天天有喜',70);
注:
- 构造函数的prototype属性,在 ES6 的“类”上面继续存在。事实上,类的所有方法都定义在类的prototype属性上面
- ES6里面class没有提升功能,必须在定义好了以后再执行。在ES5,用函数模拟可以,默认函数提升 (类没有预解析,必须先定义再使用 )
- 类必须使用new调用,否则会报错。
- List item实例的属性除非显式定义在其本身(即定义在this对象上),否则都是定义在原型上(即定义在class上)
类的其它用法
01、在“类”的内部可以使用get和set关键字,对某个属性设置存值函数和取值函数,拦截该属性的存取行为
class Person{
constructor() {
}
get aaa(){
return `aaa的属性值`; //用于返值
}
set aaa(val){
console.log(`设置aaa属性,值为:${val}`); //设置好aaa的值后供后面调用时捕获
}
}
let p1=new Person();
p1.aaa='123';
console.log(p1.aaa)
02、静态方法: 所有在类中定义的方法,都会被实例继承。如果在一个方法前,加上static关键字,就表示该方法不会被实例继承,而是直接通过类来调用,这就称为“静态方法”。
class Person{
constructor() {
}
showName(){
return `这是showName方法`;
}
static aaa(){
return `这是静态方法`; //就是类身上的方法,不受p1限制,只为Person服务
}
}
let p1=new Person();
console.log(p1.showName());
console.log(p1.aaa());
03、函数表达式:与函数一样,类也可以使用表达式的形式定义。
04、类的继承
class Person{
constructor(name) {
this.name=name;
}
showName(){
return `名字为:${this.name}`;
}
}
// ES6:子类继承父类****
class Student extends Person{
constructor(name,skill) {
super(name); //相当于将父类的构造函数在执行一遍
this.skill=skill; //子类的属性
}
showSkill(){ //子类的方法
return `学生的技能为:${this.skill}`;
}
}
// 调用
let stu1=new Student("Strive","逃学");
console.log(stu1.showSkill());
console.log(stu1.showName());