ES6 Class(类)

一、ES6 类的定义

ES5 构造函数的写法:

function Point(x, y) {
    this.x = x;
    this.y = y;
}

ES6 引入了 Class(类),通过class关键字,可以定义类。

class Point {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }
}

这里,ES6 的 Point 类的构造方法对应前面 ES5 的构造函数 Point,代码中的 constructor 是构造方法。

关于 constructor

constructor 是类的默认方法,通过 new 命令生成对象实例时,自动调用该方法。

一个类必须有 constructor 方法,如果没有显式定义,一个空的 constructor 方法会被默认添加:

class Point {
}

// 等同于
class Point {
    constructor() {}
}

二、ES6 类的实例

生成类的实例与 ES5 一样,也是用 new 命令。

但构造函数的实例不用 new 也可以执行,而类必须用 new,否则会报错:

class Point {
  // ...
}

// 报错
var point = Point(2, 3);

// 正确
var point = new Point(2, 3);

三、ES6 类的继承

 1、extends 关键字实现继承

class Parent{
  constructor(lastName='Liu'){
    this.lastName=lastName;
  }
}
class Child extends Parent{
}
console.log(new Child());

// 输出结果

2、super() 方法继承传递参数

class Parent{
  constructor(lastName='Liu'){
    this.lastName=lastName;
  }
}
class Child extends Parent{
  constructor(lastName){
    super(lastName);
  }
}
console.log(new Child('Chen'));

// 输出结果

四、getter 和 setter

与 ES5 一样,在“类”的内部可以使用 get 和 set 关键字,对某个属性设置取值函数和存值函数,拦截该属性的存取行为

1、getter(取值函数)

class Parent{
  constructor(name='Winnie'){
    this.name=name;
  }
  get longName(){
    return 'Liu'+this.name;
  }
}
let getterName=new Parent();
console.log(getterName.longName);  // LiuWinnie

2、setter(存值函数)

class Parent{
  constructor(name='Winnie'){
    this.name=name;
  }
  get longName(){
    return 'Liu'+this.name;
  }
  set longName(value){
    this.name=value;
  }
}
let setterName=new Parent();
setterName.longName='Honey';
console.log(setterName.longName);    // LiuHoney

五、静态方法

类相当于实例的原型,所有在类中定义的方法,都会被实例继承。

但如果在一个方法前加上 static 关键字,则该方法不会被实例继承,而是直接通过类来调用,这种方法称为静态方法。

1、static 关键字的使用

class Parent{
  static tell(){
    console.log('hello');
  }
  tell(){
    console.log('world');
  }
}
Parent.tell();    // hello

以上代码还可以看出静态方法可以与非静态方法重名

2、静态属性

class Parent {
}

Parent.lastName = 'Liu';
console.log(Parent.lastName);  // Liu

上面代码为 Parent 类定义了一个静态属性 lastName

猜你喜欢

转载自www.cnblogs.com/Leophen/p/11234191.html