面向过程就是分析出解决问题所需要的步骤,然后用函数把这些步骤一步步实现,使用的时候再一个一个的一次调用就可以了。
例如:将大象装进冰箱,面向过程的做法是
1.把冰箱门打开
2.把大象装进去
3.关上冰箱门
面向过程,就是按照我们分析好的步骤,按步骤来执行就可以了。
面向对象是把事务分解成一个个对象,然后由对象之间分工合作。
例如:将大象装进冰箱,面向对象的做法是:先找出对象,并写出这些对象的功能
1.大象对象 -> 进去
2.冰箱对象 -> 打开、关闭
3.使用大象和冰箱的功能
面向对象是以对象功能来划分问题,而不再是步骤。
在 ES6 中新增加了类的概念,可以使用 class 关键字声明一个类,然后以这个类来实例化对象。
来看一个例子
doctype html>
<html>
<head>
<meta charset="UTF-8">
head>
<body>
<script>
// 1、定义一个老师类
class Teacher {
// 3、构造函数使用 name 和 age 这两个参数,接收实例化传过来的值
constructor(name, age) {
// 4、赋值给当前对象的属性 name 和 age
this.name = name
this.age = age
}
}
// 2、类通过实例化(new) 变成对象,并传了两个值
const teacherH = new Teacher('黄老师', 18)
// var teacherL = new Teacher('刘老师', 20)
// 5、输出这个对象
console.log(teacherH)
// console.log(teacherL)
script>
body>
html>

constructor:构造方法,当类被实例化时,会自动运行。构造方法中,可以接收参数,用于初始化属性。name 和 age 是这个类的共有属性doctype html>
<html>
<head>
<meta charset="UTF-8">
head>
<body>
<script>
class Teacher {
// 1、定义公共方法
teach() {
console.log('我会讲课')
}
// 1、定义公共方法
program() {
console.log('我会写代码')
}
}
// 2、通过 new 实例化两个对象
const teacherH = new Teacher()
const teacherL = new Teacher()
// 3、通过对象去调用类里面的方法
teacherH.teach()
teacherL.program()
script>
body>
html>

练习:修改上述代码,输出结果是
黄老师今年 18 岁了,会讲课;刘老师今年 20 岁了,会写代码
doctype html>
<html>
<head>
<meta charset="UTF-8">
head>
<body>
<script>
class Teacher {
constructor(name) {
this.name = name
}
// 2、接收参数并输出结果
teach(courses) {
console.log(this.name + '会讲' + courses)
}
}
const teacherH = new Teacher('黄老师')
// 1、调用方法的时候传入参数值
teacherH.teach('全栈课程')
script>
body>
html>

使用 extends 可以实现类的继承,继承后的子类,拥有父类所有的属性、方法。
doctype html>
<html>
<head>
<meta charset="UTF-8">
head>
<body>
<script>
// 1、定义一个父类
class Animal {
eat() {
console.log('我会吃')
}
run() {
console.log('我会跑')
}
}
// 2、定义一个子类,子类继承父类
class Bird extends Animal{
fly(){
console.log('我会飞')
}
}
// 3、实例化子类
const bird = new Bird()
// 4、调用方法
bird.eat()
bird.run()
bird.fly()
// 5、实例化父类
const pig = new Animal()
// pig.eat()
// pig.run()
// pig.fly()
script>
body>
html>
doctype html>
<html>
<head>
<meta charset="UTF-8">
head>
<body>
<script>
class Animal {
// 2、在父类的构造方法中接收 name 参数
constructor(name) {
this.name = name
}
eat() {
// 3、输出结果
console.log('我是' + this.name + ',我会吃')
}
}
class Bird extends Animal {
fly() {
console.log('我会飞')
}
}
// 1、实例化子类并传参数值
const bird = new Bird('鹦鹉波利')
// 4、调用方法
bird.eat()
script>
body>
html>
如果我想把
鹦鹉波利传给子类的构造方法该怎么办呢?这时,我们就得用到super关键词
doctype html>
<html>
<head>
<meta charset="UTF-8">
head>
<body>
<script>
class Animal {
constructor(name) {
this.name = name
}
eat() {
// 3、输出结果
console.log('我是' + this.name + ',我会吃')
}
}
class Bird extends Animal {
// 1、子类构造方法接收参数
constructor(name) {
// 2、使用 super 关键字去调用父类的 constructor,并把 name 值传过去
super(name)
}
// fly() {
// // 3、在子类的方法中去调用父类的方法
// super.eat()
// }
// eat() {
// console.log('我是子类,我会吃')
// }
}
const bird = new Bird('鹦鹉波利')
bird.eat()
// bird.fly()
script>
body>
html>
当子类和父类有相同的方法名时,子类会将父类的方法覆盖掉。如果需要保留父类方法的内容,并且在子类增加新的功能,可以使用
super