1.类声明
class Person {
// 类构造器
constructor(name) {
this.name = name;
}
//定义类方法
sayName() {
console.log(this.name);
}
}
let person = new Person("Bob");
person.sayName(); // Bob
2.为什么使用类
(1)函数声明可以被提升,而类声明和let类似,不能被提升。真正执行声明语句之前,它们会一直存在临时死区中。
(2)类声明中的所有代码将自动运行在严格模式下,且无法强行让代码脱离严格模式执行。
(3)在自定义类型汇总,需要通过Object.defineProperty()方法手工指定某个方法为不可枚举;而在类中,所有方法都是不可枚举的。
3.类表达式
let Person = class {
// 类构造器
constructor(name) {
this.name = name;
}
//定义类方法
sayName() {
console.log(this.name);
}
}
let person = new Person("Bob");
person.sayName(); // Bob
4.作为一等公民的类
function CreateObject(classDef) {
return new classDef();
}
let obj = createObject(class {
sayHi(){
console.log('Hi');
}
}
obj.sayHi() // Hi
5.访问器属性
class Person {
// 类构造器
constructor(name) {
this.name = name;
}
//getter方法
get getName() {
return this.name;
}
//setter方法
set setName(name) {
this.name = name;
}
}
let person = new Person("Bob");
console.log(person.getName); // Bob
6.可计算成员名称
let methodName = 'sayName';
class Person {
// 类构造器
constructor(name) {
this.name = name;
}
[methodName]() {
console.log(this.name);
}
}
let person = new Person("Bob");
person.sayName(); // Bob
7.生成器方法
class Person {
*createIterator() {
yield 1;
yield 2;
yield 3;
}
}
let person = new Person("Bob");
let iterator = person.createIterator();
console.log(iterator.next().value); // 1
console.log(iterator.next().value); // 2
console.log(iterator.next().value); // 3
8.静态成员
class Person {
//静态变量
static type = "human";
//静态方法
static getType() {
console.log(this.type);
}
}
console.log(Person.type); // human
Person.getType(); // human
9.继承
class Rectangle {
constructor(length, width) {
this.length = length;
this.width = width;
}
getArea() {
return this.length * this.width;
}
}
class Square extends Rectangle {
//若定义子类构造器则必须调用super方法否则会报错
constructor(length) {
super(length,length);
}
}
let square = new Square(2);
console.log(square.getArea()); //4