结构
在class的{}里,只能使用构造函数,静态方法,静态属性,实例方法
class Per {
//动态属性 一个构造函数
constructor (name, age) {
this.name = name
this.age = age
}
//直接写
showName() {
console.log('我是实例方法');
}
static info = '这是静态属性'
static show () {
console.log('我是静态方法');
}
}
var p2 = new Per('zs', 18)
console.log(p2.name); //调用动态属性
p2.showName() //调用实例方法
console.log(Per.info);//调用静态属性
Per.show()//调用静态方法
类的继承
子类需要使用到super关键字指向父类,super关键字表示调用父类的构造方法,也就是父类constructor中的内容
class Per {
constructor (name, age) {
this.name = name
this.age = age
}
showName () {
console.log("我是实例方法")
}
}
class Gdr extends Per {
constructor (name, age, hobby) {
super(name, age)
this.hobby = hobby
}
}
var aGdr = new Gdr('sansan', 20, '读书')
console.log(aGdr.name) // sansan
aGdr.showName()//我是实例方法
ES5 用构造函数实现继承
通过构造函数+原型对象模拟实现继承,也叫组合继承
核心原理:通过call()
把父类型的this
指向子类型的this
function Father (name, age) {
this.name = name
this.age = age
}
function Son (name, age) {
father.call(this, name, age)
}
var son1 = new Son('刘德华', 18)
console.log(son1.name) //刘德华
console.log(son1)