# JavaScript 新语法特性
# 1. 类
基本使用:
class Point {
x: number;
y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
add(point: Point) {
return new Point(this.x + point.x, this.y + point.y);
}
}
继承(extends):
class Point3D extends Point {
z: number;
constructor(x: number, y: number, z: number) {
super(x, y);
this.z = z;
}
add(point: Point3D) {
const point2D = super.add(point);
return new Point3D(point2D.x, point2D.y, this.z + point.z);
}
}
静态(static):
// 类属性
class Foo {
static num: number;
static add() {
// ...
}
}
成员访问修饰符:
- public: 默认
- protect
- private
抽象(abstract):
- 可以用在类和成员上
- abstract 类不能实例化,必须继承并实现
构造器(constructor):
class Foo {
x: number;
constructor(x: number) {
this.x = x;
}
}
// 简写:给 x 添加访问修饰符,即可编译为上面的代码
class Foo {
constructor(public x: number) {
}
}
属性初始化:
class Foo {
num = 0; // ES7 提供的特性
}
# 2. 箭头函数
说明:
- 箭头函数也称为 胖箭头(
->
瘦箭头,=>
胖箭头)或 lambda 函数
修复 this:
箭头函数 捕获上下文的 this
class Person { constructor(public age: number) { } growOld = () => { this.age++; } } const person = new Person(0); const growOld = person.growOld; growOld(); console.log(person.age); // 1
继承:
class Parent {
constructor(public num1: number) {
}
// 子类只能通过 this.add 获取父类的 add
add = (num: number) => {
return this.num1 + num;
}
}
class Sun extends Parent {
addOfParent = this.add;
add = (num: number): number => {
return this.addOfParent(num);
}
}
console.log(new Sun(10).add(20))
# 3. rest 参数(剩余参数)
function printRest(num1, num2, ...nums) {
console.log(nums);
}
printRest(1, 2); // []
printRest(1, 2, 3, 4) // [3, 4]
# 4. 解构
解构与 rest:
const { z, ...point2D } = { x: 1, y: 2, z: 3 }
console.log(z); // 3
console.log(point2D); // { x: 1, y: 2 }
const [num1, num2, ...others] = [1, 2, 3, 4, 5];
console.log(others); // [3, 4, 5]
# 5. 扩展运算符
const point2D = { x: 1, y: 2 };
// 在对象中展开
const point3D = { ...point2D, z: 3 };
console.log(point3D); // { x: 1, y: 2, z: 3 }
const numArr1 = [ 1, 2 ];
// 在数组中展开
const numArr2 = [ ...numArr1, 3, 4 ]
console.log(numArr2); // [1, 2, 3, 4]
const args = [1, 2, 3];
function sum(num1, num2, num3) {
return num1 + num2 + num3;
}
// 在实参列表中中展开
sum(...args);
上一篇: 下一篇:
本章目录