ECMAScript出现了许多有趣的新特性,梳理一下:
1.支持constant声明
ES5中,想实现constant变量必须通过修改var的property实现
1 2 3 4 5 |
Object.defineProperty(this, "PI", { value: 3.1415926, configurable: false, writable: false }); |
2.支持块作用域声明let,
JS只有函数作用域,没有块作用域,var声明有变量提升的效果,即如果var声明了一个未声明过的变量,会自动将此声明提升到顶端,所以想实现块作用域在ES5中是通过闭包的形式。
1 |
(function(param) {})(i); |
同时ES6也支持了块级作用域的函数
3.一种function的新写法
function中支持this的使用
1 2 3 4 5 6 7 |
nums.forEach(function(v) { return foo(v); }); nums.forEach(v => { foo(v) }); |
4.undefined参数默认配置
ES6:
1 2 3 |
function(x, y = 7, z = 10) { return x + y + z; } |
等效于ES5:
1 2 3 4 5 6 7 8 9 |
function(x, y, z) { if (y === undefined) { y = 7; } if (z === undefined) { z = 10; } return x + y + z; } |
5.支持剩余参数写法
即...p写法会被解释为
1 |
p.prototype.slice |
ES6:
1 2 3 4 |
function f (x, y, ...a) { return (x + y) * a.length } f(1, 2, "hello", true, 7) === 9 |
ES5:
1 2 3 4 5 |
function f (x, y) { var a = Array.prototype.slice.call(arguments, 2); return (x + y) * a.length; }; f(1, 2, "hello", true, 7) === 9; |
6.可以直接在字符串中加入${表达式}
即console.log("Error: ${e.toString()}");
7.引用
1 2 3 4 5 6 7 |
//lib/math.js export function sum(x, y) {return x + y}; export var pi = 3.1415926; //app.js import * as math from "lib/math" console.log(math.sum(math.pi, math.pi);); |
8.支持class 继承,setter、getter
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
class Shape { constructor (id, x, y) { this.id = id; this.move(x, y); } move (x, y) { this.x = x; this.y = y; } } class Rectangle extends Shape { constructor (id, x, y, width, height) { super(id, x, y); this.width = width; this.height = height; } set width(width) {this.width = width} get width() {return this.width} } class Circle extends Shape { constructor (id, x, y, radius) { super(id, x, y); this.radius = radius; } } |
9.支持Promise Generators(待学习)
10.bufferArray
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
class Example { constructor (buffer = new ArrayBuffer(24)) { this.buffer = buffer } set buffer (buffer) { this._buffer = buffer this._id = new Uint32Array (this._buffer, 0, 1) this._username = new Uint8Array (this._buffer, 4, 16) this._amountDue = new Float32Array(this._buffer, 20, 1) } get buffer () { return this._buffer } set id (v) { this._id[0] = v } get id () { return this._id[0] } set username (v) { this._username[0] = v } get username () { return this._username[0] } set amountDue (v) { this._amountDue[0] = v } get amountDue () { return this._amountDue[0] } } let example = new Example() example.id = 7 example.username = "John Doe" example.amountDue = 42.0 |