第一阶段.模块二:学习笔记-es6的类进阶

文章说明:文章内容为学习笔记,学徒之心,仅为分享; 如若有误,请在评论区指出,如若您觉得文章内容对您有一点点帮助,请点赞、关注、评论,共享

上一篇:第一阶段.模块二:学习笔记-es6的类基础
下一篇:第一阶段.模块二:学习笔记-TypeSrcipt的类

es6 的类

es6 中创建类的时候,类名的首字母要大写 例如:class Animal{}
es6 中创建类的时候,类里面必有 constructor(){} 函数
es6 中创建类的时候,constructor 函数中的 this 指向的是 通过类 创建的实例

1-es5 类的继承
// es5中类的继承,也就是构造函数的继承
// es5中类的继承,需要用到原型链才可以实现
// 构造函数Food
function Food() {
    this.type = '构造函数Food'
}

Food.prototype.getType = function () {
    return this.type
}
// 构造函数Vegetables
function Vegetables(name) {
    this.name = name

}
Vegetables.prototype = new Food()
const vegetables = new Vegetables('蔬菜洋葱')
console.log(vegetables.getType()) // 构造函数Food
console.log(vegetables.name) // 蔬菜洋葱


2-es6 类的继承
// 使用关键字 extends 和 super() 来实现 子类 继承 父类
// 子类 可以继承 父类的 静态方法
// super() 必须放在 constructor(){}函数里面的 第一行
// 类 是可以 多继承的

// 父类
class Partner1 {
    constructor(name) {
        this.name = name
    }
    getName() {
        return this.name
    }
}

// 子类,并且继承父类
class Child extends Partner1 {
    constructor(name, age) {
        super(name)
        this.age = age
    }
    getAge() {
        return this.age
    }
}

const child = new Child('花花', 23)
console.log(child.getAge()) // 23
console.log(child.getName()) // 花花
// child实例既是Child类的实例,也是Partner1的实例
console.log(child instanceof Partner1) // true
console.log(child instanceof Child) // true

3-Object.getPrototypeOf()方法
// 可以获取构造函数的原型对象
4-类中 super()方法

1、作为函数使用

super()方法 代表 父类的 constructor(){}方法
父类的 constructor(){}方法里面的属性,就是子类 constructor(){}方法里面的属性

2、作为对象使用,可以调用父类的方法和属性,通过 super.父类方法

在普通方法、constructor(){}方法中,super.父类方法 指向的是父类的原型对象
在静态方法中,super.父类方法 指向的是父类本身

3、类在继承的时候,父类中的 this,指向的是子类的实例

class Partner1 {
    constructor() {
        this.name = '父类的name属性'
    }
    getName() {
        // this指向的是子类的实例,子类实例中没有name属性,
        // 这时候this指向的就是父类的name属性
        // 父类也没有name属性,就返回undefined
        console.log(this.name) // this指向的是子类的实例
    }
}

class Child extends Partner1 {
    constructor() {
        super()
        this.name = '子类的name属性'
    }
    getAge() {
        // supter作为对象,在普通方法中使用,指向的是父类的原型对象
        // 子类中 调用 父类的 getName()方法
        super.getName()
    }
}

const child = new Child()
child.getAge() // 子类的name属性
5-类的 prototype 属性和 [ proto ]属性

const obj = new Object() // 构造函数Object的实例obj
console.log(obj.__proto__ === Object.prototype) // true

子类的 --proto-- 指向的是父类本身
子类的 prototype 属性的 --proto-- 指向的是父类的 prototype 属性
实例的 --proto-- 属性的 --proto-- 指向的是父类实例的 --proto--

6-原生构造函数的继承

1、 es5 中原生的构造函数是无法继承的

Boolean Number String Array Date Function RegExp Error Object 。。。

2、 es6 中原生的构造函数是可以继承的

class myArray extends Array{
    constructor(...args) { 
        super(...args)
    }
}
const newArray = new myArray()
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容