【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 定义类的语法糖,但是从开发者的角度而言,开发更有效率了,代码可阅读性大大提升。
相关文章
- 深入理解ES6之《块级作用域绑定》
- Js基础知识7-Es6新增对象Map和set数据结构
- ES6的新特性
- [Kotlin] Class / Abstract class / Example
- [Javascript] ES6 Class Constructors and the Super Keyword
- [ES6] Symbol
- [ES6] Extends class in ES6 vs ES5 subclass
- [ES6] 19. for ... of
- [ES6] 11. String Templates
- Es6系列之module and class
- Es6系列之深入generator之异常处理与相互调用
- TypeScript class 表达式 - Class expression
- Atitit js es5 es6新特性 attilax总结
- Atitit js版本es5 es6新特性
- 使用 Babel 将基于 ES6 的 SAP UI5 的代码转译成传统 JavaScript 代码
- audio currentTime 时间戳转换(es6语法)
- JS 高级(七)ES6解构、class、promise
- JavaScript前端经典面试题之ES6面试题汇总es6