封装、继承、多态
类好比函数一样,
class User {
constructor(name){//相当与函数的行参/次函数默认执行
this.name = name
}
}
let hd = new User('qihuanran')
conole.log(hd.name) // qihuanran
构造函数是可以循环属性方法的通过for in包括原形上的 、类不可以循环方法和属性。
类默认就是严格模式⬇️**
class hd{
show() {
function th() {
conole.log(this)
}
th()
}
}
let n = new hd()
conole.log(n.show()) //undefined
函数在非严格模式下是window
function a() {
console.log(this)
}
let hd = new a()
console.log(hd) // window
静态属性
static
class User {
static host: '192.168.1.1'
get(url) {
return this.host + `/${url}`
}
}
let api = new User()
console.log(api.get('text'))
// 192.168.1.1/text
调用静态方法不需要实例化类,可以直接调用
class user {
static get() {
console.log('qihuanran')
}
}
user.get()
// qihuanran
super原理
super就是访问我的父级类
let user = {
name: 'qihuanran'
show() {
conole.log(this.name) // 此时this指向为admin
}
}
let Admin = {
__proto__: user // admin继承user父级
name: 'xiangjun'
show() {
this.__proto__.show.call(this) //改变user的this指向当前admin
}
}
admin.show() //xiangjun
super主要的作用是原形攀升、由于父级的this需要子级通过call来绑定到子级,当多层嵌套的时候this就会发生错误,是找不到的。所以super可以继续攀升。
如果父类有constructor那么子类想调用父类就必须使用super
super.show()调用父类方法