Home >Web Front-end >JS Tutorial >Code examples for classes and objects in ES6
This article brings you code examples about classes and objects in ES6. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
1.Basic definition and generated instance
{ class Parent { constructor(name = 'haha') { this.name = name; } } let parent = new Parent('v'); console.log('构造函数和实例', parent); // Parent {name: "v"} }
2.Inheritance
{ class Parent { constructor(name = 'haha') { this.name = name; } } class Child extends Parent { } console.log('继承', new Child()); // Child {name: "haha"} }
3.Inheritance passing parameters
{ class Parent { constructor(name = 'haha') { this.name = name; } } class Child extends Parent { constructor(name = 'child') { // super()方法,用来解决 继承怎么传递参数(怎么覆盖父类的参数) // super的参数列表就是父类构造函数的参数列表,如果参数为空,就采用父类的参数默认值 super(name); // super必须放在构造函数第一行 this.type = 'child'; } } console.log('继承传递参数', new Child('hello')); // Child {name: "hello", type: "child"} }
4.getter setter
{ class Parent { constructor(name = 'haha') { this.name = name; } // longName 是一个属性,不是方法 get longName() { return 'lu-' + this.name; } // longName 是一个属性,不是方法 set longName(value) { this.name = value; } } let person = new Parent(); console.log('getter', person.longName); // lu-haha person.longName = 'hello'; console.log('setter', person.longName); // lu-hello }
5.static method
{ class Parent { constructor(name = 'haha') { this.name = name; } // static 关键字用来定义静态方法 static tell() { console.log('do tell'); } } // 静态方法,直接通过类去调用,不是通过实例 Parent.tell(); // do tell }
6.static Attribute
{ class Parent { constructor(name = 'haha') { this.name = name; } } // 直接在类上定义静态属性 Parent.type = 'test'; // 读取静态属性时,也是直接拿类读取 console.log(Parent.type); // test }
The above is the detailed content of Code examples for classes and objects in ES6. For more information, please follow other related articles on the PHP Chinese website!