跳到主要内容

2. ECMAScript 和 TypeScript 概述

ECMAScript 2015+ 的功能

2.2.7 使用类进行面向对象编程

类的声明:

class Book {
constructor(title, pages, isbn) {
this.title = title;
this.pages = pages;
this.isbn = isbn;
}
printIsbn() {
console.log(this.isbn);
}
}

只需要使用 class 关键字,声明一个有 constructor 函数和诸如 printIsbn 等其他函数的类。ES2015 的类是基于原型语法的语法糖。

1.继承

ES2015 中,类的继承也有简化的语法

class ITBook extends Book { // {1}
constructor (title, pages, isbn, technology) {
super(title, pages, isbn); // {2}
this.technology = technology;
}

printTechnology() {
console.log(this.technology);
}
}
let jsBook = new ITBook(’学习JS算法’, '200', '1234567890', 'JavaScript');
console.log(jsBook.title);
console.log(jsBook.printTechnology());

我们可以用 extends 关键字扩展一个类并继承它的行为(行{1})。在构造函数中,我们也可以通过 super 关键字引用父类的构造函数(行{2})。

2.使用属性存取器

ES2015 也可以为类属性创建存取器函数。虽然不像其他面向对象语言(封装概念),类的属性不是私有的,但最好还是遵循一种命名模式。

class Person {
constructor(name) {
this._name = name; // {1}
}
get name() {
// {2}
return this._name;
}
set name(value) {
// {3}
this._name = value;
}
}

let lotrChar = new Person("Frodo");
console.log(lotrChar.name); // {4}
lotrChar.name = "Gandalf"; // {5}
console.log(lotrChar.name);
lotrChar._name = "Sam"; // {6}
console.log(lotrChar.name);

要声明 get 和 set 函数,只需要在我们要暴露和使用的函数名前面加上 get 或 set 关键字(行{2}和行{3})。我们可以用相同的名字声明类属性,或者在属性名前面加下划线(行{1}),让这个属性看起来像是私有的。

然后,只要像普通的属性一样,引用它们的名字(行{4}和行{5}),就可以执行 get 和 set 函数了。

2.2.8 乘方运算符

ES2016 中引入了**运算符,用来进行指数运算

const area = 3.14 * r ** 2;

// 同下面几种写法
const area = 3.14 * Math.pow(r, 2);
const area = 3.14 * r * r;