使用js很久了, 一直有用过类,但是对它的理解也是云里雾里,今天小小做了个总结
JavaScript 中常常会有想要实现一个复杂的功能,需要定义多个变量/常量写多个功能函数来实现一个复杂的功能,如果这个功能是多处常用的那么要写多次,在后端中有对类的定义,但是前端中以前靠构造函数来实现。这样所有需要使用的变量接口统一写在一个集合的对象上,即清晰又方便。
1. 构造函数方法
function Person(name, age, gender) {
this.name = name
this.age = age
this.gender
function say () {
alert('hello world')
}
}
2. 类方法
class Person {
constructor(name, age, gender) {
this.name = name
this.age = age
this.gender = gender
}
say () {
alert('hello world')
}
}
类的继承 extends
class Developer extends Person {
constructor(name, age, gender, job) {
super(name, age) // 调用父类的construct
this.job = job
}
}
注: 在子类构造函数中,只有调用了super函数才可以使用this 因为子类实例基于父类实例