let命令也用于声明对象,但是作用域为局部
{
let a = 10;
var b = 1;
}
在函数外部可以获取到b,获取不到a,因此例如for循环计数器就适合使用let。
const用于声明一个常量,设定后值不会在改变
const PI = 3.1415;
PI // 3.1415
PI = 3;
强行对其进行重新赋值会报错。
为了统一集合类型,ES6标准引入了新的iterable类型,Array、Map和Set都属于iterable类型,具有iterable类型的集合可以通过for…or循环来遍历
var a = ['A', 'B', 'C'];
var s = new Set(['A', 'B', 'C']);
var m = new Map([[1, 'x'], [2, 'y'], [3, 'z']]);
for(var x of a){ // 遍历Array
alert(x);
}
for(var x of s){ // 遍历Set
alert(x);
}
for(var x of m){ // 遍历Map
alert(x[0] + '=' + x[1]);
}
Map的相关操作方法如下,Set同理:
var m = new Map(); // 空Map
m.set('Adam', 67); // 添加新的key-value
m.set('Bob', 59);
m.has('Adam'); // 是否存在key 'Adam': true
m.get('Adam'); // 67
m.delete('Adam'); // 删除key ‘Adam’
m.get('Adam'); // undefined
ES6允许按照一定模式,从数组和对象中提取值,对变量进行赋值,这被称为解构(Destructuring)。
例如数组:
let [a, b, c] = [1, 2, 3];
// 等同于
let a = 1;
let b = 2;
let c = 3;
对象的结构赋值: 获取对象的多个属性并且使用一条语句将它们赋给多个变量。
var {
StyleSheet,
Text,
View
} = React;
等同于
var StyleSheet = React.StyleSheet
...
ES6中新增箭头操作符用于简化函数的写法,操作符左边为参数,右边为具体操作和返回值。
var sum = (num1, num2) => { return num1 + num2 }
// 等同于
var sum = function(num1, num2){
return num1 + num2;
};
箭头函数还修复了this的指向,使其永远指向词法作用域:
var obj = {
birth: 1999,
getAge: function(){
var b = this.birth; // 1999
var fn = () => new Date().getFullYear() - this.birth; //this指向obj对象
return fn();
}
}
obj.getAge(); // 25
通过它可以将数组作为参数直接传入函数:
var people = ['Wayou', 'John', 'Sherlock'];
function sayHello(people1, people2, people3){
console.log(`Hello ${people1},${people2},${people3}`);
}
// 改写为
sayHello(...people); // 输出: Hello Wayou,John,Sherlock
在函数定义时可以通过…rest获取定义参数外的所有参数:
function foo(a, b, ...rest){
console.log('a = ' + a);
console.log('b = ' + b);
console.log(rest);
}
foo(1, 2, 3, 4, 5);
// 结果:
// a = 1
// b = 2
// Array [3, 4, 5]
ES6提供了更接近传统语言的写法,引入Class(类)这个概念,作为对象的模板。通过class关键字,可以定义类,与多数传统语言类似。
// 定义类
class Point {
constructor(x, y){
this.x = x;
this.y = y;
}
toString(){
return '(' + this.x + ', ' + this.y + ')';
}
}
自动解析数组或对象中的值,不用以对象的方式返回。
var [x, y] = getVal(), // 利用函数返回值进行解构
[name,,age] = ['wayou','male','secrect']; // 利用数组进行解构
function getVal(){
return [1, 2];
}
console.log('x:' + x + ' ,y:' + y); // 输出x:1,y:2
console.log('name: ' + name + ', age:' + age); // 输出: name:wayou, age: secrect
// 创建promise
var promise = new Promise(function(resolve, reject){
// 进行一些异步或耗时操作
if(/*如果成功*/){
resolve("Stuff worked!");
} else {
reject(Error("It broke"));
}
});
// 绑定处理程序
promise.then(function(result){
// promise成功的话会执行这里
console.log(result); // "Stuff worked!"
}, function(err){
// promise失败会执行这里
console.log(err); // Error: "It broke"
});
ES6里面Promise可以用来避免异步操作函数里的嵌套回调(callback hell)问题,’.then().then()’; 适用于ajax网络请求、读取localstorage等操作。
常规的回调嵌套:
Parse.User.logIn("user", "pass", {
success: function(user){
query.find({
success: function(results){
results[0].save({key: value}, {
success: function(result){
// the object was saved.
},
error: function(result, error){
// An error occurred.
}
})
},
error: function(error){
// An error occurred.
}
})
},
error: function(user, error){
// An error occurred.
}
})
Promise的实现过程:
Parse.User.logIn("user", "pass").then(function(user){
returnquery.find();
}).then(function(results){
return results[0].save({ key: value });
}).then(function(result){
// the object was saved.
}, function(error){
// there was some error.
});
直接到错误的地方就不在继续执行.then,而是跳出执行error状态下的function。
另一个promise的例子:
下面是一个简单的用setTimeout()实现的异步延迟加载函数:
setTimeout(function(){
console.log('Yay!');
}, 1000);
在ES6中,我们可以用promise重写:
var wait1000 = new Promise(function(resolve, reject){
setTimeout(resolve, 1000);
}).then(function(){
console.log('Yay!');
})
或者用ES6的箭头函数:
var wait1000 = new Promise((resolve, reject) => {
setTimeout(resolve, 1000);
}).then(() => {
console.log('Yay!');
})
到目前为止,代码的行数从三行增加到五行,并没有任何明显的好处,确实,如果我们有更多的嵌套逻辑在setTimeout()回调函数中,我们将发现更多好处:
setTimeout(function(){
console.log('Yay!');
setTimeout(function(){
console.log('Wheeyee!');
}, 1000)
}, 1000)
在ES6中我们可以用promises重写:
var wait1000 = () => new Promise((resolve, reject) => {setTimeout(resolve, 1000)});
wait1000()
.then(function(){
console.log('Yay!')
return wait1000()
})
.then(function(){
console.log('Wheeyee!')
});