面向对象
一、面向对象和面向过程的区别:
1、面向过程: 强调过程步骤
缺陷:(1)问题规模:随着问题规模的增大,代码逐渐难以控制;
(2)复用性差;
2、面向对象: 强调对象
三大特性:封装、继承、多态;
面向对象分析问题的步骤:
(1)找出问题拥有的对象
(2)抽象出这些对象的属性和方法创建类
(3)各个对象各司其职执行代码
二、类和对象的概念:
1、类:是具有相同属性和行为的对象的集合(模板);
类定义了对象的属性和方法,通过类可以实例化多个该类的对象,每个对象的属性值不同;
2、对象:根据类的属性和行为创建的实例化。
三、ES5的方法创建类(普通构造方法):
//构造函数
function Student(name,age,id){
//this:代表new出来的对象
//成员属性
this.name = name;
this.age = age;
this.id = id;
//成员方法
this.study = function(){
console.log(this.name + "好好学习,天天向上");
}
//如果一个成员方法引用了其他成员属性和方法,访问时必须加this前缀
this.showValue = function(){
console.log(this.name,this.age,this.id);
this.study();
}
}
//对象的定义
let s1 = new Student("刘东洋",18,"9527");
//对象使用属性和方法,
this 的作用:
(1)事件:触发事件的元素
(2)普通函数:调用该方法的对象
(3)构造函数:new出来的对象
四、ES6的方法创建类:
class 类名{
类体;
}
//构造类
class Student{
//构造方法:定义属性
constructor(name,age,id) {
this.name = name;
this.age = age;
this.id = id;
}
//行为的定义
study(){
console.log(this.name+"study");
}
}
//构造对象
let s = new Student("安心如",17,"008");
//对象使用属性和方法
console.log(s.name,s.age,s.id); //安心如 17 008
s.study(); //安心如study
五、组合(关联):一个类的属性,是另一个类的对象
一个复杂的对象可以有若干个较为简单的小对象构成;
//创建一个生日类
class Birthday{
constructor(y,m,d) {
this.y = y;
this.m = m;
this.d = d;
}
showValue(){
console.log(this.y,this.m,this.d);
}
}
//创建一个学生类
class Student{
constructor(name,id,bir) {
this.name = name;
this.id = id;
this.bir = bir;
}
showValue(){
console.log(this.name,this.id);
this.bir.showValue();
}
}
let b = new Birthday(1997,9,3);
let stu = new Student("王五",8013,b);
stu.showValue(); //王五 8013 1997 9 3
六、依赖:一个类的成员函数的参数,是另一个类的对象
案例:有一辆小汽车行驶在一条公路上,计算这辆小汽车以60KM/小时的速度,行驶1000KM需要多久。
//创建一个小汽车类
class Car{
constructor(speed) {
this.speed = speed;
}
time(r){ //依赖
return r.length/this.speed;
}
}
//创建一个路类
class Road{
constructor(length) {
this.length = length;
}
}
let c = new Car(60);
let r = new Road(1000);
console.log(c.time(r)); //16.666666666666668
七、小明手里有两张牌,左手红桃A,右手黑桃K。
问:当小明交换左右手的牌后,两只手分别剩下什么牌?
见第十六天代码