ES6的面向对象编程以及ES6中的类和对象

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

一、面向对象

1、面向对象

1是一种开发思想并不是具体的一种技术

2一切事物均为对象在项目中主要是对象的分工协作

2、对象的特征

1对象是属性和行为的结合体

2属性体现对象的静态特征、

3行为体现对象的动态特征(具体体现为函数/方法)

3、面向对象的三大特征

1封装性对象时属性和行为的封装体

2继承性在基类父类中已经定义的属性或行为子类可以继承使用

3多态性同一个信息传递给不同的对象呈现的效果也是不同的

二、ES6中的类和对象

1、类在ES6中引入类的概念使用class关键字进行定义

class 类名{

        属性

        方法

}

2、ES6中类和对象的关系

1类是对象的抽象类抽取了对象的公共部分

2对象是类的实例化对象是类的具体实例

3、ES6中类的构造函数

使用constructor作为类的构造函数用于初始化对象。在定义类的时候若没有显式的定义constructorjs会自动生成一个无参的构造函数(constructor(){}) 

 class Student{
    constructor(id,name,age,sex){   //constructor用来初始化对象的属性
        this.id = id,
        this.name = name,
        this.age = age,
        this.sex = sex
    }
    show(){
       console.log(`学号:${this.id} 姓名:${this.name} 年龄:${this.age} 性别:${this.sex}`);
    }
}
let stu1 = new Student('001','小王',20,'男');
console.log(stu1);
stu1.show();

 

 注通过类创建对象new 类名([参数])

1创建对象时不能显式调用constructor在new 类名()创建对象时默认调用了constructor

2在定义类时若没有写constructor则js会自动生成无参的constructor

三、ES6中类的继承

1、基类被继承的类也可称为父类或超类

2、子类由基类派生的类又称为派生类

3、继承的用法通过extends关键字实现

class 父类名{

        构造方法

        普通方法

}

class 子类名 extends 父类名{

        构造方法

        普通方法

}

4、super关键字代表是父类在类的继承过程中访问父类的构造函数、普通函数

class Father{
    constructor(name,sex){
        this.name= name,
        this.sex = sex
    }
    display(){
        console.log(`姓名${this.name} 性别${this.sex}`);
    }
}

class Son extends Father{
    constructor(name,sex,address,phone){
        super(name,sex),
        this.address = address,
        this.phone = phone
    }
    show(){
        console.log(`姓名:${this.name} 性别${this.sex} 地址:${this.address} 电话${this.phone}`);
    }
}

let son1 = new Son('小黑','男','西安','13198302930')
son1.show();

5、子类的普通方法与父类的普通方法同名时子类方法覆盖父类的方法

类中的普通方法又称为实例方法或成员方法

        class Animal{
            eat(food){
                console.log(`${food}`);
            }
            sleep(){
                console.log('在睡觉');
            }
        }
        class Rabbit extends Animal{
            eat(){
                super.eat('兔子吃草')
            }
        }
        class Tiger extends Animal{
            eat(){
                super.eat('老虎吃肉')
            }
        }
        let rabbit = new Rabbit()
        rabbit.eat();
        rabbit.sleep();
        let tiger = new Tiger();
        tiger.eat();
        tiger.sleep();

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6