ECMAScript 6 是JavaScript的下一个规范,正处在疾速开辟当中,大部份已完成了,估计将在2014年正式宣布。Mozilla将在这个规范的基础上,推出JavaScript 2.0。
ECMAScript 6 的目的,是使得JavaScript能够用来编写庞杂的运用程序、函数库和代码的自动生成器(code generator)。
最新的浏览器已部份支撑ECMAScript 6 的语法,能够经由过程《ECMAScript 6 浏览器兼容表》检察浏览器支撑状况。
一、ECMAScript 6 新内容一览
let, const (定义块级局部变量), 函数在块级域中
解构:
let {x, y} = pt; let [s, v, o] = triple();
(如能够let pt = {x:2, y:-5}
).参数设置默认设置:
function f(x, y=1, z=0) {...}
rest:
function g(i, j, ...r) { return r.slice(i, j); }
(而不是猖獗地运用arguments).spread:
let a = [0,1,2,3]
,o = new Something(...a);
proxies:
let obj = Proxy.create(handler, proto)
. 简朴地说,就是类对象元素的标记重载.weak map:
let map = new WeakMap
. 当你有轮回运用的时刻用它.generators:
function* gen() { yield 1; yield 2; }
事实上, gen() 返回一个有next()属性的对象迭代器:
for (var [key, val] of items(x)) { alert(key + ',' + val); }
. Iterators 能够是 generators 或许 proxies.array and generator comprehension:
[a+b for (a in A) for (b in B)]
(array comprehension),(x for (x of generateValues()) if (x.color === 'blue'))
(generator expression).二进制数据:
const Pixel = new StructType({x:uint32, y:uint32, color:Color})
(此处Color自身就是一个构造范例),new ArrayType(Pixel, 3)
.类语法, 包括
extends
,prototype
, andsuper
:class Point extends Base { constructor(x,y) { super(); this[px] = x, this[py] = y; this.r = function() { return Math.sqrt(x*x + y*y); } } get x() { return this[px]; } get y() { return this[py]; } proto_r() { return Math.sqrt(this[px] * this[px] + this[py] * this[py]); } equals(p) { return this[px] === p[px] && this[py] === p[py]; } }
模块:
module math { export function sum(x, y) { return x + y; } export var pi = 3.141593; } import {sum, pi} from math; alert(sum(pi,pi));
quasis: multiline, 可扩大的预处理字符串.
You are ${age} years old.
.// The following regexp spans multiple lines. re`line1: (words )* line2: \w+` // It desugars to: re({raw:'line1: (words )*\nline2: \w+', cooked:'line1: (words )*\nline2: \w+'})
二、参考资料
http://espadrine.github.io/Ne… espadrine
http://javascript.ruanyifeng…. ruanyifeng
ECMAScript 6系列文章请移步:http://barretlee.com/ES6/