面向对象OOP 1.首先找出对象,写出这些对象功能
面向对象的特性 1.封装性 2.继承性 3.多态性
一、ES6中的类和对象
1、对象
js中是一组无序的相关属性和方法的集合,所有的事物都是对象
2、类 class
公共部分
3、类constructor构造函数
constructor会返回实例 ,不需要调用会自动执行
<script>
//1 创建类 class 创建一个 类
class Star {
constructor(uname, age) {
this.uname = uname;
this.age = age;
}
//创建方法sing
//要求 1 类里面所有的函数不需要写function
//2 多个函数方法之间不需要加逗号分隔
sing(song) {
console.log('我唱歌');
console.log(this.uname + song);
}
}
//2 利用类创建对象 new
new Star();
var ldh = new Star('刘德华', 18);
console.log(ldh.uname);
console.log(ldh.age);
console.log(ldh);
ldh.sing('冰雨')
</script>
二、类的继承
1、expends
2、super关键字
super关键字用来访问和调用对象父类上的哈描述,可以调用父类的构造函数,也可以调用父类的普通函数
<script>
//1 类的继承
// class Father {
// constructor() {
// }
// money() {
// console.log(100);
// }
// }
// class Son extends Father {
// }
// var son = new Son();
// son.money();
class Father {
constructor(x, y) {
this.x = x;
this.y = y;
}
sum() {
console.log(this.x + this.y);
}
}
class Son extends Father {
constructor(x, y) {
super(x, y);//用于调用父类中的构造函数
}
}
var son = new Son(1, 2);
son.sum();
</script>
<script>
// super 关键字调用父类普通函数
class Father {
say() {
return '我是爸爸';
}
}
class Son extends Father {
say() {
console.log('我是儿子');
console.log(super.say() + '的儿子');
// super.say() 就是调用父类中的普通函数 say()
}
}
var son = new Son();
son.say();
</script>
<script>
class Father {
constructor(x, y) {
this.x = x;
this.y = y;
}
sum() {
console.log(this.x + this.y);
}
}
//子类继承父类加法方法 同时 拓展减法方法
class Son extends Father {
constructor(x, y) {
//利用super 调用父亲的构造函数
//super 必须在子类this之前调用
super(x, y);
this.x = x;
this.y = y;
}
subtract() {
console.log(this.x - this.y);
}
}
var son = new Son(5, 3);
son.subtract();
son.sum();
</script>
子类在构造函数中使用super,必须放到this前面(必须先调用父类的构造方法,再使用子类的构造方法)