class extends constructor static super get/set
javascript
{
// 基本定义和生成实例
class Parent {
constructor(name = 'wcd') {
this.name = name
}
}
let v_parent = new Parent('v')
console.log('构造函数和实例', v_parent) // 构造函数和实例 Parent { name: 'v' }
}
{
// 继承
class Parent {
constructor(name = 'wcd') {
this.name = name
}
}
class Child extends Parent {}
console.log('继承', new Child()) // 继承 Child { name: 'wcd' }
}
{
// 继承传递参数
class Parent {
constructor(name = 'wcd') {
this.name = name
}
}
class Child extends Parent {
constructor(name = 'child') {
super(name)
this.type = 'child'
}
}
console.log('继承传递参数', new Child('hello')) // 继承传递参数 Child { name: 'hello', type: 'child' }
}
{
// getter, setter
class Parent {
constructor(name = 'wcd') {
this.name = name
}
// 这里是属性,不是方法
get longName() {
return 'yx' + this.name
}
set longName(value) {
this.name = value
}
}
let v = new Parent()
console.log('getter', v.longName) // getter yxwcd
v.longName = 'hello'
console.log('setter', v.longName) // setter yxhello
}
{
// 静态方法,不能在类的实例上调用静态方法,而应该通过类本身调用
class Parent {
constructor(name = 'wcd') {
this.name = name
}
static tell() {
console.log('tell') // tell
}
}
Parent.tell()
}
{
// 静态属性
class Parent {
constructor(name = 'wcd') {
this.name = name
}
static tell() {
console.log('tell')
}
}
Parent.type = 'test'
console.log('静态属性', Parent.type) // 静态属性 test
}