ES6的class 构造函数

前言

这东西私下学了n遍了,还是老记不住,这次空闲时间在学习react,常用到class,好记性不如烂笔头啊,所以专门记录一下,方便之后查看;

正文

1. 普通函数

// func语法
function Demo(x, y) {
    this.x = x
    this.y = y
}
Demo.prototype.test = function () {
    return `${this.x}是X的值,${this.y}是Y 的值`
}
let str = new Demo(2, 3).test()
console.log(str)//2是X的值,3是Y 的值

2. 使用class改写

class Demo2 {
    constructor(x, y) {
        this.x = x
        this.y = y
    }
    test() {
        return `${this.x}是X的值,${this.y}是Y 的值`
    }
    static chanage() {
        return '测试是否能被继承'
    }
}
let str2 = new Demo2(5, 6).test()
let str3 = Demo2.chanage(2)
// let str4 = new Demo2(5, 6).chanage()//error  不能被继承
console.log(str2)//5是X的值,6是Y 的值
console.log(str3)//测试是否能被继承
2.1 class特征

使用class改写——class写法只是让对象原型的写法更加清晰、更像面向对象编程的语法而已。对比可知,test() class中的所有方法都定义在类的prototype属性上,多个属性不可枚举;

  1. constructor 是构造函数,new的时候自动调用,不写会默认添加一个空的constructor(){},默认返回实例对象(this);
  2. 调用方式,new Demo2(1,2);
  3. 类不存在变量提升;
  4. static 静态方法,不会被实例继承,而是直接通过类来调用;

3. class继承

class Demo3 {
    constructor(x, y) {
        this.x = x
        this.y = y
    }
    test() {
        return `${this.x}是X的值,${this.y}是Y 的值`
    }
    static isChanage() {
        return '测试是否能被继承'
    }
}
class Child1 extends Demo3 {
    constructor(x, y, z) {
        super(x, y)
        // console.log(super.test(),'1');
        this.z = z
    }
    toAdd() {
        return `${this.z}是z的值,${this.y + this.z + this.x}是和的值`
    }
}
let str4 = new Child1(5, 6, 7).test()
let str5 = new Child1(5, 6, 7).toAdd()
console.log(str4); //5是X的值,6是Y 的值
console.log(str5); //7是z的值,18是和的值
// let str6 = new Child1(5, 6, 7).isChanage() //error
let str6 = Child1.isChanage() 
console.log(str6);//测试是否能被继承
3.1 继承的特征
  1. class通过extends关键字的继承;
  2. 子类必须先调用super方法,拿到this 对象,才能做其他操作,在普通方法中指向父类原型对象,可以取到父类的属性;
  3. static 静态方法,会被子类继承,可以直接调用;

4. super函数

未完。。。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值