ES6:类 class

ES6引入了class,其跟其它语言的class大致相同,JS中的class本质是function
它可以看做是语法糖

1.类的声明

class name {
	//...
}

2.类的定义

//匿名类
const a = class {
	//...
}

//命名类
const b = class name {
	//...
}

3.实例化

class name {
	//...
}

const ex = new name();

注意
1️⃣ 函数存在函数提升,尽管类的本质是function,但是他没有提升,在访问类时必须要先声明
2️⃣ 不可重复声明

4.类的构造函数

类中的构造函数为 constructor() 方法实现

class student {
	constructor(name, classroom) {
		this.name = name;
		this.classroom = classroom;
	}
}

const Tom = new student('Tom', '3年2班');

在这里插入图片描述

5.类的方法

如何在类中添加方法,如下所示:

class student {
	constructor(name, classroom) {
		this.name = name;
		this.classroom = classroom;
	} //注意这里是没有逗号的

	info() {
		console.log(`我叫${this.name},我是${this.classroom}的`);
	}
}

const Tom = new student('Tom', '3年2班');

在这里插入图片描述

6.静态方法

静态方法是只能由类调用的方法(就比如这里只能用student调用而不是Tom),就好比 Array.form() 方法,它不能用于 [1, 2, 3].form() ,只能使用在原型上的方法

JS中使用 static 关键字定义静态方法:

class student {
	constructor(name, classroom) {
		this.name = name;
		this.classroom = classroom;
	} //注意这里是没有逗号的

	info() {
		console.log(`我叫${this.name},我是${this.classroom}的`);
	}
	
	static description() {
		console.log('student info');
	}
}

const Tom = new student('Tom', '3年2班');

在这里插入图片描述

7.set()与get()方法

class student {
	constructor(name, classroom) {
		this.name = name;
		this.classroom = classroom;
	} //注意这里是没有逗号的

	info() {
		console.log(`我叫${this.name},我是${this.classroom}的`);
	}
	
	static description() {
		console.log('student info');
	}

	set gradeInfo(value) {
		this.grade = value;
	}

	get gradeInfo() {
		return `grade is ${this.grade}`;
	}
}

const Tom = new student('Tom', '3年2班');

在这里插入图片描述

8.类的继承

先定义一个父类Animal

class Animal {
	constructor(name) {
		this.name = name;
		this.belly = [];
	}
	
	eat(food) {
		this.belly.push(food);
	}
}

继承使用extends关键字:

class Dog extends Animal {
	constructor(name) {
		super();//必须写在this前
		this.name = name;
	}
	
	bark() {
		console.log('汪汪汪!');
	}
}

const dog = new Dog('dog');

在这里插入图片描述

发布了26 篇原创文章 · 获赞 0 · 访问量 598

猜你喜欢

转载自blog.csdn.net/weixin_43856797/article/details/104075830