zl程序教程

您现在的位置是:首页 >  后端

当前栏目

【ES6(2015)】Class (类)

ES6 Class 2015
2023-09-11 14:19:17 时间

Javascript是一种基于对象(object-based)的语言,你遇到的所有东西几乎都是对象。但是,它又不是一种真正的面向对象编程(OOP)语言,因为它的语法中没有class(类)。

对于面向对象编程而言,更关注类的声明、属性、方法、静态方法、继承、多态、私有属性。

1. 声明类

ES5 中声明(构造方法):

let Animal = function(type) {
	// 属性
    this.type = type
    // 方法
    this.walk = function() {
        console.log( `I am walking` )
    }
}
Animal.prototype.run = function() {
    console.log( `I am running` )
}

let dog = new Animal('dog')
let monkey = new Animal('monkey')

ES6 声明Class类:

class Animal {
	// 构造函数
    constructor(type) {
        this.type = type
    }
    // 方法
    walk() {
        console.log( `I am walking` )
    }
}
let dog = new Animal('dog')
let monkey = new Animal('monkey')

class 的方式是 function 方式的语法糖

2. Setters & Getters

对于类中的属性,可以直接在 constructor中通过 this 直接定义,还可以直接在类的顶层来定义:

class Animal {
    constructor(type, age) {
        this.type = type
        this._age = age
    }
    get age() {
        return this._age
    }
    set age(val) {
        this._age = val
    }
}

设置制度属性只需要把set方法去掉即可。

set/get可以控制在满足条件下才执行:

let #age = 1
class Animal {
    constructor(type) {
        this.type = type
    }
    get age() {
        return #age
    }
    set age(val) {
        if (val > 0 && val < 10) {
            #age = val
        }
    }
}

3. 静态方法

静态方法是面向对象最常用的功能,在 ES5 中利用 function 实现的类是这样实现一个静态方法的。

let Animal = function(type) {
    this.type = type
    this.walk = function() {
        console.log( `I am walking` )
    }
}

Animal.eat = function(food) {
    console.log( `I am eating` )
}

在 ES6 中使用 static 的标记是不是静态方法,代码如下:

class Animal {
    constructor(type) {
        this.type = type
    }
    walk() {
        console.log( `I am walking` )
    }
    static eat() {
        console.log( `I am eating` )
    }
}

静态方法是直接用类名访问的。

4. 继承

在 ES5 中怎么实现继承:

// 定义父类
let Animal = function(type) {
    this.type = type
}
Animal.prototype.walk = function() {
    console.log( `I am walking` )
}

// 定义子类
let Dog = function() {
    // 初始化父类
    Animal.call(this, 'dog')
    this.run = function() {
        console.log('I can run')
    }
}
// 继承
Dog.prototype = Animal.prototype

ES6 中的继承:

// 父类
class Animal {
    constructor(type) {
        this.type = type
    }
    walk() {
        console.log( `I am walking` )
    }
}
// 子类继承父类
class Dog extends Animal {
  constructor () {
    super('dog')
  }
  run () {
    console.log('I can run')
  }
}

虽然 ES6 在类的定义上仅是 ES5 定义类的语法糖,但是从开发者的角度而言,开发更有效率了,代码可阅读性大大提升。