01-面向对象编程
一、面向对象特性
面向对象的特性:封装性、继承性、多态性
优点:易维护、易复用、易扩展、低耦合、使系统更加灵活、更加易于维护
缺点:性能比面向过程低
对象是由属性和方法组成的
二、创建类和对象
<script>
//1.创建类class
class Star {
constructor(name, age) {
this.name = name //谁调用this就指向谁
this.age = age
}
sayHello() {
console.log('Hello World!');
}
}
//2.利用类创建对象
var hzp = new Star('胡振鹏', 19)
hzp.sayHello()
console.log(hzp);
</script>
运行结果:Hello World! Star 对象
三、类的继承
<script>
//1.类的继承
class Father {
constructor(x, y) {
this.x = x
this.y = y
}
sum() {
console.log(this.x + this.y);
}
money() {
console.log(100);
}
}
class Son extends Father { //子类继承父类
constructor(x, y) {
super(x, y) //调用父类的构造函数
}
}
var son = new Son(1, 2)
son.money()
son.sum()
//1.继承中 如果实例化输出一个方法 先看子类有没有这个方法 如果有就执行子类的
//2.继承中 如果子类里面没有 就去查找父类的 如果有就去执行父类的
</script>
运行结果: 100 3
四、子类继承父类方法同时扩展自己的方法
<script>
class Father {
constructor(x, y) {
this.x = x
this.y = y
}
sum() {
console.log(this);
console.log(this.x + this.y);
}
}
class Son extends Father {
constructor(x, y) { //super必须放在this之前
//利用super调用父类的构造函数
super(x, y)
this.x = x
this.y = y
}
subtract() {
console.log(this);
console.log(this.x - this.y)
}
}
var son = new Son(3, 1)
son.subtract()
son.sum()
</script>
运行结果: Son对象 2 Son对象 4

浙公网安备 33010602011771号