在以前javascript 不支持 class 类的写法,在现在可以用 class 来命名一个类给这个类实现一个构造方法,父类可以背子类继承,一种面向对象的实现模式。
1 2 3 4 5 6
| class Parent { constructor(name = "I am class") { this.name = name; } }
|
创建一个类
1 2 3 4 5 6 7 8 9 10 11 12
| { class Parent { constructor(name = "lelei") { this.name = name; } } let parent = new Parent("less"); console.log(parent); }
|
类的继承 extends
1 2 3 4 5 6 7 8 9 10
| { class Parent { constructor(name = "lelei") { this.name = name; } } class Child extends Parent { } console.log(new Child()); }
|
类的继承传递参数 super
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| { class Parent { constructor(name = "lelei") { this.name = name; } } class Child extends Parent { constructor(name = "child") { super(name); this.type = "type"; } } console.log(new Child("hello")); }
|
getter setter 方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| { class Parent { constructor(name = "lelei") { this.name = name; } get newName() { return 'new ' + this.name; } set newName(value) { this.name = value; } } let parent = new Parent(); console.log(parent.newName); parent.longName = 'hello'; console.log(parent.newName); }
|
静态方法和静态属性的创建和使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| { class Parent { constructor(name = "lelei") { this.name = name; } static tell() { console.log("I am static method"); } } Parent.tell(); Parent.type = 'I am static attr'; console.log(Parent.type); }
|