一、ESMAScritp 6 基础
1.1 Constants
const PI = 3.141593
PI > 3.0
1.2 变量作用范围
for (let i = 0; i < a.length; i++) {
let x = a[i]
…
}
for (let i = 0; i < b.length; i++) {
let y = b[i]
…
}
let callbacks = []
for (let i = 0; i <= 2; i++) {
callbacks[i] = function () { return i * 2 }
}
callbacks[0]() === 0
callbacks[1]() === 2
callbacks[2]() === 4
1.3 函数作用范围
{
function foo () { return 1 }
foo() === 1
{
function foo () { return 2 }
foo() === 2
}
foo() === 1
}
1.4 箭头函数:return简写
odds = evens.map(v => v + 1)
pairs = evens.map(v => ({ even: v, odd: v + 1 }))
nums = evens.map((v, i) => v + i)
相当于ECMAScript 5原有的写法:
odds = evens.map(function (v) { return v + 1; });
pairs = evens.map(function (v) { return { even: v, odd: v + 1 }; });
nums = evens.map(function (v, i) { return v + i; });
1.5 箭头函数:闭包语法(closure syntax)
nums.forEach(v => {
if (v % 5 === 0)
fives.push(v)
})
相当于ECMAScript 5原有的写法:
nums.forEach(function (v) {
if (v % 5 === 0)
fives.push(v);
});
1.6 箭头函数:当前上下文对象
this.nums.forEach((v) => {
if (v % 5 === 0)
this.fives.push(v)
})
<=> ECMAScript 5写法:
// variant 1
var self = this;
this.nums.forEach(function (v) {
if (v % 5 === 0)
self.fives.push(v);
});
// variant 2
this.nums.forEach(function (v) {
if (v % 5 === 0)
this.fives.push(v);
}, this);
// variant 3 (since ECMAScript 5.1 only)
this.nums.forEach(function (v) {
if (v % 5 === 0)
this.fives.push(v);
}.bind(this));
1.7 参数默认值
function f (x, y = 7, z = 42) {
return x + y + z
}
f(1) === 50
1.8 预留参数
function f (x, y, ...a) {
return (x + y) * a.length
}
f(1, 2, "hello", true, 7) === 9
1.9 …的扩展操作
var params = [ "hello", true, 7 ]
var other = [ 1, 2, ...params ] // [ 1, 2, "hello", true, 7 ]
function f (x, y, ...a) {
return (x + y) * a.length
}
f(1, 2, ...params) === 9
var str = "foo"
var chars = [ ...str ] // [ "f", "o", "o" ]
<=> ECMAScript 5写法:
var params = [ "hello", true, 7 ];
var other = [ 1, 2 ].concat(params); // [ 1, 2, "hello", true, 7 ]
function f (x, y) {
var a = Array.prototype.slice.call(arguments, 2);
return (x + y) * a.length;
};
f.apply(undefined, [ 1, 2 ].concat(params)) === 9;
var str = "foo";
var chars =