js中对于类的基本认识

Class

在es6之前,是通过定义函数和函数的原型对象去实现类型

//before es6
function Person(name){
    this.name = name
}
Person.prototype.say = function(){
    console.log(`hi	${this.name}`)
}

//es6  定义一个Person类型
class Person{
    constructor(name){	//构造函数
        this.name = name
    }
    
    say(){
        console.log(this.name)
    }
}

静态成员

在我们类中的方法,分为实例方法和静态方法,实例方法需要实例对象进行调用,静态方法直接通过类型本身去调用。

es6新增static关键字

class Person{
    constructor(name){	//构造函数
        this.name = name
    }
    
    say(){
        console.log(this.name)
    }
    
    static create(name){
        return new Person(name)
    }
}

const tom = Person.create('tom')

类的继承

在es6之前是通过原型链去进行类的继承,在es6之后是通过extends进行类的继承

class Person{
    constructor(name){	//构造函数
        this.name = name
    }
    
    say(){
        console.log(this.name)
    }
}

class Student extends Person{
    constructor(name,number){
        super(name)
        this.number = number
    }
    hello(){
        super.say()//会调用父节点的方法
        console.log('my school number is ${this.number}')
    }
}

const s = new Student('jack','100')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值