和其它面向对象编程语言一样,ES6 正式定义了 class 类以及 extend 继承语法糖,并且支持静态、派生、抽象、迭代、单例等,而且根据 ES6 的新特性衍生出很多有趣的用法。
一、类的基本定义
基本所有面向对象的语言都支持类的封装与继承,那什么是类?
类是面向对象程序设计的基础,包含数据封装、数据操作以及传递消息的函数。类的实例称为对象。
ES5 之前通过函数来模拟类的实现如下:
// 构造函数function Person(name) { this.name = name;}// 原型上的方法Person.prototype.sayName = function(){ console.log(this.name);};// new 一个实例var friend = new Person("Jenny");friend.sayName(); // Jennyconsole.log(friend instanceof Person); // trueconsole.log(friend instanceof Object); // true
总结来说,定义一个类的思路如下:
1.需要构造函数封装数据
2.在原型上添加方法操作数据,
3.通过New创建实例
ES6 使用class关键字定义一个类,这个类有特殊的方法名[[Construct]]定义构造函数,在 new 创建实例时调用的就是[[Construct]],示例如下:
/*ES6*/// 等价于 let Person = class {class Person { // 构造函数 constructor(name) { this.name = name; } // 等价于Person.prototype.sayName sayName() { console.log(this.name); }}console.log(typeof Person); // functionconsole.log(typeof Person.prototype.sayName); // functionlet friend = new Person("Jenny");friend.sayName(); // Jennyconsole.log(friend instanceof Person); // trueconsole.log(friend instanceof Object); // true
上面的例子中class定义的类与自定义的函数模拟类功能上貌似没什么不同,但本质上还有很大差异的:
函数声明可以被提升,但是class类声明与let类似,不能被提升; 类声明自动运行在严格模式下,“use strict”; 类中所有方法都是不可枚举的,enumerable 为 false。二、更灵活的类
类和函数一样,是JavaScript的一等公民(可以传入函数、从函数返回、赋值),并且注意到类与对象字面量还有更多相似之处,这些特点可以扩展出类更灵活的定义与使用。
2.1 拥有访问器属性
对象的属性有数据属性和访问属性,类中也可以通过get、set关键字定义访问器属性:
class Person { constructor(name) { this.name = name; } get value () { return this.name + this.age } set value (num) { this.age = num }}let friend = new Person("Jenny");// 调用的是 setterfriend.value = 18// 调用的是 getterconsole.log(friend.value) // Jenny18
2.2 可计算的成员名称
类似 ES6 对象字面量扩展的可计算属性名称,类也可以用[表达式]定义可计算成员名称,包括类中的方法和访问器属性:
新闻热点
疑难解答
图片精选