之前或多或少的看过一些react的代码,也自己写了一些demo,会用一些简单的语法,最近疫情闲在家中,打算系统的学习一下,在此记录一些学习笔记。
关于class写法
相比于ES5中通过构造函数生成实例对象,ES6 提供了更接近传统语言的写法,引入了 Class(类)这个概念,作为对象的模板。通过class关键字,可以定义类。
在此之前,我们通常的构造函数的写法
function Person(name, age){
this.name = name
this.age = age
}
Person.staticAttribute = '构造函数的【静态属性/静态方法】,不可被new的对象访问'
Person.prototype = {
say: function(){
console.log('通过new出来的对象可以访问到的属性叫做【实例属性/实例方法】', this.name, this.age)
}
}
var xiaoming = new Person('小明', 18)
console.log(xiaoming)
console.log(xiaoming.staticAttribute)
xiaoming.say()
![](https://img.haomeiwen.com/i7662941/d2f3deba843ea06f.png)
在写构造函数的时候,通常会涉及到【构造函数】、【静态属性】、【实例属性/实例方法】、【实例对象】这些东西。
这里用class语法来实现一次上面的功能。
class Person {
constructor (name, age) { // 当我们不写constructor时会有一个默认的constructor空函数
this.name = name
this.age = gae
}
// 声明静态属性用static
static staticAttribute = '构造函数的【静态属性/静态方法】,不可被new的对象访问'
static staticFunction = function () {
console.log('我是静态方法')
}
// 这里声明【实例属性/实例方法】就简单了很多
say() {
console.log('通过new出来的对象可以访问到的属性叫做【实例属性/实例方法】', this.name, this.age)
}
}
这里打印出Person和他的prototype
![](https://img.haomeiwen.com/i7662941/c3c109415e0f6cbc.png)
再来new出class定义的构造函数
var xiaoming = new Person('小明', 18)
console.log(xiaoming)
console.log(xiaoming.staticAttribute)
xiaoming.say()
![](https://img.haomeiwen.com/i7662941/21d950be227671b7.png)
class被称作语法糖,其原理还是使用构造函数来实现的
关于extends继承
写react使用最多的一个方法就是class xxx extends xxx{}
这里涉及到了继承的写法
class Person {
constructor(name, age){
this.name = name
this.age = age
// 这里的super写法等价于上面的两行语句
// super(name, age)
// super()函数不传参数时会执行
// this.name = undefiend;
// this.age = undefiend;
}
}
class Man extends Person {
manFun() {
console.log('Man独有的【实例方法】')
}
}
var he = new Man('辣个男人', 777)
console.log(he)
![](https://img.haomeiwen.com/i7662941/97518d6a9d3d5fd4.png)
总结:class ... extends ...
语句是ES6的语法糖,简化了构造函数的生成,也简化了继承父类的流程,同时对于代码的可读性也有了提升。
其实我们在写react组件时就是在写一个构造函数,面向对象的优势在react里体现的很明显,比较适合业务的设计模式也会在react中发挥的很好。
网友评论