一、class核心语法
1、公有属性
2、构造函数
3、公有方法
class Person {
// 1、公有属性
name
// 2、构造函数
constructor(name) {
this.name = name
}
// 3、公有方法
say() {
console.log("say")
console.log(this.name)
}
}
const p = new Person("jack")
二、继承
extends : 继承
super :调用父类构造函数
// 父类
class Person {
name
constructor(name) {
this.name = name
}
say() {
console.log("say")
console.log(this.name)
}
}
// 继承
class Student extends Person {
constructor(name, age) {
super(name)
this.age = age
}
bay() {
console.log("bay")
}
// 同名方法 就近原则
say() {
console.log("重写 say")
}
}
// 创建实例对象
const s = new Student("张三")
三、静态属性和方法
1、静态属性:static定义 类名.属性名直接调用
2、私有属性:#开头 调用#开头
3、外部无法直接访问私有属性和方法,要在外部使用,可以在静态方法中调用私有方法
4、chrome浏览器可以调用私有属性和方法,是方便调试
class Person {
// 静态属性和方法
static stInfo = '静态属性'
static stMethod() {
console.log('静态方法')
}
// 私有属性和方法
#reInfo = '私有属性'
#reMethod() {
console.log('私有方法')
}
// 访问私有属性和方法
getreInfo() {
console.log(this.#reInfo)
this.#reMethod()
}
}
// 访问静态属性和方法
console.log(Person.stInfo)
Person.stMethod()
// 访问私有属性和方法
const p = new Person
p.getreInfo()
四、寄生组合式继承
通过构造函数继承属性
通过原型链继承方法
// 构造函数 父类
function Person(name) {
this.name = name
}
Person.prototype.say = function () {
console.log("通过原型链继承了方法")
}
//----------寄生组合式继承------------
// 通过构造函数继承属性
function Student(name) {
Person.call(this, name) // this 指向子类实例 name 使用父类定义属性
}
// 通过原型链继承方法
const pertotype = Object.create(Person.prototype, { //参数2:可选,覆盖源对象的特定属性和方法
constructor: {
value: Student
}
})
Student.prototype = pertotype
// 子类实例化对象
const s = new Student("小明")
// --------Object.create() 静态方法 ------------
// 将一个对象作为原型,创建一个新的对象
// 参数1:源对象
// 参数2:可选,覆盖源对象的特定属性和方法
const foo = {
name: "apple",
eat() {
console.log("吃苹果")
}
}
const test = Object.create(foo)
// test.eat()输出 吃苹果
// 第二个参数,重新定义eat
const test2 = Object.create(foo, {
eat: {
value() {
console.log("吃香蕉")
}
}
})