面向对象

一、面向对象和面向过程的区别:
1、面向过程: 强调过程步骤
缺陷:(1)问题规模:随着问题规模的增大,代码逐渐难以控制;
(2)复用性差;
2、面向对象: 强调对象
三大特性:封装、继承、多态;
面向对象分析问题的步骤:
(1)找出问题拥有的对象
(2)抽象出这些对象的属性和方法创建类
(3)各个对象各司其职执行代码
二、类和对象的概念:
1、类:是具有相同属性和行为的对象的集合(模板);
类定义了对象的属性和方法,通过类可以实例化多个该类的对象,每个对象的属性值不同;
2、对象:根据类的属性和行为创建的实例化。

三、ES5的方法创建类(普通构造方法):

  1. //构造函数
  2. function Student(name,age,id){
  3. //this:代表new出来的对象
  4. //成员属性
  5. this.name = name;
  6. this.age = age;
  7. this.id = id;
  8. //成员方法
  9. this.study = function(){
  10. console.log(this.name + "好好学习,天天向上");
  11. }
  12. //如果一个成员方法引用了其他成员属性和方法,访问时必须加this前缀
  13. this.showValue = function(){
  14. console.log(this.name,this.age,this.id);
  15. this.study();
  16. }
  17. }
  18. //对象的定义
  19. let s1 = new Student("刘东洋",18,"9527");
  20. //对象使用属性和方法,

this 的作用:
(1)事件:触发事件的元素
(2)普通函数:调用该方法的对象
(3)构造函数:new出来的对象

四、ES6的方法创建类:
class 类名{
类体;
}

  1. //构造类
  2. class Student{
  3. //构造方法:定义属性
  4. constructor(name,age,id) {
  5. this.name = name;
  6. this.age = age;
  7. this.id = id;
  8. }
  9. //行为的定义
  10. study(){
  11. console.log(this.name+"study");
  12. }
  13. }
  14. //构造对象
  15. let s = new Student("安心如",17,"008");
  16. //对象使用属性和方法
  17. console.log(s.name,s.age,s.id); //安心如 17 008
  18. s.study(); //安心如study

五、组合(关联):一个类的属性,是另一个类的对象
一个复杂的对象可以有若干个较为简单的小对象构成;

  1. //创建一个生日类
  2. class Birthday{
  3. constructor(y,m,d) {
  4. this.y = y;
  5. this.m = m;
  6. this.d = d;
  7. }
  8. showValue(){
  9. console.log(this.y,this.m,this.d);
  10. }
  11. }
  12. //创建一个学生类
  13. class Student{
  14. constructor(name,id,bir) {
  15. this.name = name;
  16. this.id = id;
  17. this.bir = bir;
  18. }
  19. showValue(){
  20. console.log(this.name,this.id);
  21. this.bir.showValue();
  22. }
  23. }
  24. let b = new Birthday(1997,9,3);
  25. let stu = new Student("王五",8013,b);
  26. stu.showValue(); //王五 8013 1997 9 3

六、依赖:一个类的成员函数的参数,是另一个类的对象
案例:有一辆小汽车行驶在一条公路上,计算这辆小汽车以60KM/小时的速度,行驶1000KM需要多久。

  1. //创建一个小汽车类
  2. class Car{
  3. constructor(speed) {
  4. this.speed = speed;
  5. }
  6. time(r){ //依赖
  7. return r.length/this.speed;
  8. }
  9. }
  10. //创建一个路类
  11. class Road{
  12. constructor(length) {
  13. this.length = length;
  14. }
  15. }
  16. let c = new Car(60);
  17. let r = new Road(1000);
  18. console.log(c.time(r)); //16.666666666666668

七、小明手里有两张牌,左手红桃A,右手黑桃K。
问:当小明交换左右手的牌后,两只手分别剩下什么牌?
见第十六天代码