mdn 类
阮一峰 ES6-class
mdn-super
ES6中推出了class
类,是用来创建对象的模板。
class
可以看作是一个语法糖,它的绝大部分功能,ES5 都可以做到,新的class
写法只是让对象原型的写法更加清晰、更像面向对象编程的语法而已。
核心语法:
MDN-类
// 定义类
class Person {
// 实例属性
name
food
// 构造方法,类似于构造函数,new的时候会调用,内部的this就是实例化的对象
constructor(name, food) {
this.name = name
this.food = food
}
// 实例方法
sayHi() {
console.log(`你好,我叫${this.name},我喜欢吃${this.food}`)
}
}
const p = new Person('小黑', '西蓝花')
p.sayHi()
总结:
class核心语法:
class 类名{}
的形式来定义类方法名(){}
constructor
进行添加new 类名()
创建实例,会调用构造函数constructor
class Person{
name
food='西兰花炒蛋'
constructor(name){
this.name=name
}
sayHi(){
console.log('你好,我叫:',this.name)
}
}
// 在上一份代码的基础上继续编写下面代码
class Student extends Person {
song
constructor(name, food, song) {
// 子类构造函数使用this以前必须调用super
super(name, food)
this.song = song
}
// 添加方法
sing() {
console.log(`我叫${this.name},我喜欢唱${this.song}`)
}
}
const s = new Student('李雷', '花菜', '孤勇者')
s.sayHi()
s.sing()
总结:
class实现继承
extends
继承继承父类super
关键字调用父类的构造函数class Person {
constructor(name) {
this.name = name
}
// 通过#作为前缀添加的属性会变为私有
// 私有属性
#secret = '我有一个小秘密,就不告诉你'
// 私有方法
#say() {
// 私有属性可以在
console.log('私有的say方法')
}
info() {
// 在类的内部可以访问私有属性调用私有方法
console.log(this.#secret)
this.#say()
}
// 通过 static定义静态属性/方法
static staticMethod() {
console.log('这是一个静态方法')
console.log(this)
}
static info = '直立行走,双手双脚'
}
const p = new Person('jack')
console.log(p)
// 外部无法访问 点语法访问直接报错,通过[]无法动态获取
console.log(p['#secret'])
p.info()
// 通过类访问静态属性/方法
Person.staticMethod()
console.log(Person.info)
总结:
class 语法补充
#
static
this
是类所谓寄生组合式继承,即通过借用构造函数来继承属性,通过原型链的混成形式来继承方法。
其背后的基本思路是:不必为了指定子类型的原型而调用超类型的构造函数,我们所需要的无非就是超类型原型的一个副本而已。
核心步骤:
// 继承原型函数
function inheritPrototype(son, parent){
const prototype = object.create(parent.prototype)
prototype.constructor = son
son.prototype = prototype
}
// 父类构造函数
function Parent(name) {
this.name = name
this.foods = ['西蓝花', '西葫芦', '西红柿']
}
Parent.prototype.sayHi = function () {
console.log(this.name, `我喜欢吃,${this.foods}`)
}
// 子类借用父类的构造函数,将 this,name 参数传递给父类
function Son(name, age) {
Parent.call(this, name)
this.age = age
}
// 完成原型继承
inheritPrototype(Son,Parent)
// 可以继续在原型上添加属性/方法
Son.prototype.sayAge = function () {
console.log('我的年龄是', this.age)
}
const son1 = new Son('jack', 18)
const son2 = new Son('rose', 16)
总结:
ES5-寄生组合式继承