【ES6(2015)】Class (类)

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 定义类的语法糖,但是从开发者的角度而言,开发更有效率了,代码可阅读性大大提升。

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

优小U

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值