一、类 class
ES2015以前
ECMAScript都是通过定义函数和定义原型对象来实现类
// 比如定义一个Person类
// 先定义一个函数,作为类的构造函数
function Person(name){
this.name = name;
}
Person.prototype.say = function(){
console.log(`say ${this.name}`)
}
ES2015以后
新增了class
关键词来声明一个类
class Person{
// 如果需要在构造函数中做一些额外的逻辑
// constructor就是当前这个类的构造函数
constructor(name){
// 可以用this 访问当前类的实例对象
this.name = name
}
// 如果需要为这个类定义一些实例方法
say(){
console.log(`say ${this.name}`)
}
}
const p = new Person('tom')
p.say()
二、实例方法 VS 静态方法
在类中的方法通常分为实例方法和静态方法
-
实例方法:通过这个类构造的实例对象去调用
-
静态方法:通过类本身去调用
ES2015以前,实现静态方法是直接在构造函数上挂载方法
ES2015中新增了添加静态成员的static
关键词
class Person{
constructor(name){
this.name = name
}
say(){
console.log('实例方法say的this指向:',this)
console.log(`say ${this.name}`)
}
static create(name){
console.log('静态方法create的this指向:',this) // [Function: Person]
return new Person(name)
}
}
const tom = Person.create('tom')
tom.say()
class Person{
constructor(name){
this.name = name
}
say(){
console.log('实例方法say的this指向:',this)
console.log(`say ${this.name}`)
}
static create(name){
console.log('静态方法create的this指向:',this) // [Function: Person]
return new Person(name)
}
}
const luyu = new Person('luyu')
luyu.say()
三、继承 extends
继承是面向对象中一个很重要的特性,通过继承就能抽象出来相似的类中重复的地方
ES2015以前,大多数情况都是使用原型的方式实现继承
ES2015中,有一个专门用于类的继承的关键字:extends
class Person{
constructor(name){
this.name = name
}
say(){
console.log(`say ${this.name}`)
}
}
// 继承自Person,Student 中就会有Person中所有的成员
class Student extends Person {
// Student 构造函数中接收2个参数
constructor(name,number) {
// name 参数在父类中也需要用到
// super对象 始终指向父类,调用它就是调用了父类的构造函数
super(name)
this.number = number;
}
// 定义Student特有的成员
hello(){
super.say();
console.log(`my school number is ${this.number}`)
}
}
const tom = new Student('tom','100')
tom.hello()