ES5创建类、ES6构造方法创建类、类与类的关系:组合、类与类的关系:依赖、小明的问题

ES5创建类

用构造函数模拟类

构造方法

定义类:

function Student(name,gender,id){
        //this:new出来的对象
        this.name = name;
        this.gender = gender;
        this.id = id;
        
        this.study = function(){
            console.log("study");
        }

 //成员函数中使用其他的成员,必须加前缀this
        this.showValue = function(){
            console.log(this.name,this.gender,this.id);
            this.study();
        }
    }

 this作用

1.与事件体连用:代表触发事件的元素,

2.与普通方法连用:代表调用该函数的对象,

3.与构造函数方法的连用:代表new出来的对象

对象的创建
   new 构造方法(参数):返回了一个该类型的对象
    new:在堆空间按照Student模板开辟了一块空间
    构造方法必须和new连用

ES6

class  类名{

constructor(参数){

}

成员函数1..

成员函数2..

}

定义

构造方法

通过new关键字调用的构造方法执行时的代码块

对象的定义

let s = new Student("凢凢",'M',1);
    s.showValue();

类与类的关系:组合

组合:在定义一个类时,该类的成员属性是另一个类的对象

类与类的关系:依赖

依赖:一个类的成员方法的参数,是另一个的类的对象

use-a;

有一辆小汽车行驶在一条公路上,
    // 计算这量小汽车以60KM/小时的速度,
    // 行驶1000KM需要多久。
    
    // 面向对象分析问题的思路:
    // 1.找出该问题有几个对象    分析问题阶段
    // 2.抽象出其行为和属性构造类    编码阶段
    // 3.各个对象各司其职

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));

小明的问题

小明手里有两张牌,左手红桃A,右手黑桃K。
    // 问:当小明交换左右手的牌后,两只手分别剩下什么牌?
    
    class Card{
        constructor(color,num) {
            this.color = color;
            this.num = num;
        }
    }
    
    class Hand{
        constructor(card) {
            this.card = card;
        }
    }
    
    class Person{
        constructor(lHand,rHand) {
            this.lh = lHand;
            this.rh = rHand;
        }
        
        showCard(){
            console.log(this.lh.card.color,this.lh.card.num);
            console.log(this.rh.card.color,this.rh.card.num);
        }
        
        swapCard(){
            [this.lh.card,this.rh.card] = [this.rh.card,this.lh.card];
        }
    }
    
    let card1 = new Card("♥","A");
    let card2 = new Card("♠","K");
    
    let lh = new Hand(card1);
    let rh = new Hand(card2);
    
    let p = new Person(lh,rh);
    
    p.showCard();
    p.swapCard();
    p.showCard();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值