语法意义
class类是Es6的新特性之一,也是前端学习中非常重要的一环.
个人认为,class类的重要之处有下面三点:
1.更好的去理解面向对象的编程思想
2.很多第三方库的语法都是用class进行封装的
3.编写一些功能方法,或者是开发react所必须的
类的基本语法
构造函数的使用
在es6之前,可以使用构造函数去批量的创建具有公共方法的对象
function Person(name,age){
this.name = name
this.age = age
}
Person.prototype.getString = function(){
return `${this.name}的年龄是${this.age}`
}
let wjt = new Person('王惊涛',27)
console.log(Person,'构造函数')
console.log(wjt,'实例对象')
console.log(Person.prototype,'构造函数的prototype==>原型对象')
console.log(wjt.__proto__,'实例对象的__proto__==>原型对象')
console.log(Person.prototype === wjt.__proto__)
类的使用
class Person{
constructor(name,age){
this.name = name
this.age = age
}
getString(){
return `${this.name}的年龄是${this.age}`
}
}
let wjt = new Person('王惊涛',27)
console.log(Person,'类')
console.log(wjt,'类构建的实例对象')
console.log(Person.prototype,'类的prototype==>原型对象')
console.log(wjt.__proto__,'实例对象的__proto__==>原型对象')
console.log(Person.prototype === wjt.__proto__)
如上可知,class和构造函数其实就是一回事,所以,这就是官方的那句话,class类是构造函数的语法糖,主要是为了迎合那些熟悉其他语法中有类语法的编程人员,也是为了更加的语义化.
类里面的方法
constructor函数
定义
构造函数中我们得知,每个构造函数上都有一个constructor构造器,类里面的构造器就是这个
constructor方法是类的默认方法.每个类都有constructor方法
未显示定义
如果没有显示定义,那么class会默认定义一个
//未显示定义
class Person1{
}
//显示定义
class Person2{
constructor(){
}
}
console.log(Person1.prototype,'未显示定义')
console.log(Person2.prototype,'显示定义')
constructor自定义返回值
类里面的this
class Person{
constructor(name,age,done){
console.log(this,'constructor里面的类')
this.name = name
this.age = age
this.done = done
}
fn1 = function(){
console.log(this,'fn1函数里面的this')
}
fn2 = ()=>{
console.log(this,'fn2函数里面的this')
}
name1 = this.name
}
let wjt = new Person('王惊涛',28,function(){console.log('前端程序员')})
console.log(wjt,'wjt实例')
wjt.fn1()
wjt.fn2()
console.log(wjt.name,'wjt的name属性')
结果如下
在类中,this就是当前new出来的类实例
getter和setter
class Person{
constructor(name,age){
this.name = name
this.age = age
}
get work(){
return '前端开发者'
}
set work(val){
console.log('修改的work值',val)
}
}
let wjt = new Person('王惊涛',28)
console.log(wjt,'王惊涛实例')
wjt.age = 29
wjt.work = '全栈开发者'
结果如下
static静态方法
class Person{
constructor(name,age){
this.name = name
this.age = age
}
static fun1(){
console.log('静态方法,实例上看不到')
}
fun2(){
console.log('实例上能显示的')
}
}
let wjt = new Person('王惊涛',28)
console.log(wjt,'wjt实例对象')
console.log(wjt.fun1,'wjt.fun1')
console.log(wjt.fun2,'wjt.fun2')
结果如下
类的继承
class Person{
constructor(name,age){
this.name = name
this.age = age
this.eat = '吃饭'
this.run = '走路'
}
}
class Coder extends Person{
constructor(name,age,done){
super(name,age) //super里面定义的一定要写到最上层,里面定义的字段就是继承父的字段
this.work = '工作'
}
}
let wjt = new Coder('王惊涛',28,()=>{console.log('写代码')})
console.log(wjt,'王惊涛的实例')
结果如下