您的位置:首页 > Web前端 > JavaScript

js中对于类的基本认识

2020-07-26 22:36 68 查看

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')
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: