1class Person {
2 name // 成员属性
3 static age = 2 // 静态属性
4 constructor(name, age) {
5 this.name = name
6 this.age = age // 这里 this.age 指向实例的 age
7 }
8
9 fn() {
10 // 成员方法(原型上)
11 console.log(this.age + Person.age)
12 }
13
14 static fn1() {
15 // 静态方法 只能使用 Person.fn1()来调用
16 console.log(this.age === Person.age) // true
17 }
18}
19
20class Son extends Person {
21 constructor(name, age, sex) {
22 super(name, age) // this之前调用super
23 super.fn() // 调用父类方法
24 this.sex = sex
25 }
26
27 fn() {
28 // 重写父类方法
29 }
30
31 static ff() {
32 super.fn1() // 调用父类静态方法
33 }
34}
35
36// 不可继承常规对象。
37const Father = {
38 // ...
39}
40class Child extends Father {
41 // ...
42}
43// Uncaught TypeError: Class extends value #<Object> is not a constructor or null
44
45// 解决方案
46Object.setPrototypeOf(Child.prototype, Father)