1、设置默认参数(default parameters)
先回顾一下之前是怎么定义默认参数的:
var link = function (height, color, url) {
var height = height || 50;
var color = color || 'red';
var url = url || 'http://azat.co';
...
}
在ES6中,我们可以这样来设置默认的参数:
var link = function(height = 50, color = 'red', url = 'http://azat.co') {
...
}
2、模板对象(template literals)
之前我们是这样拼接字符串和变量的:
var name = 'Your name is ' + first + ' ' + last + '.';
var url = 'http://localhost:3000/api/messages/' + id;
在ES6中为我们提供了${ } 的方式,我们可以直接将变量写在花括号里:
var name = `Your name is ${first} ${last}. `;
var url = `http://localhost:3000/api/messages/${id}`;
3、多行字符串
在ES5中:
var roadPoem = 'Then took the other, as just as fair,nt'
+ 'And having perhaps the better claimnt'
+ 'Because it was grassy and wanted wear,nt'
+ 'Though as for that the passing therent'
+ 'Had worn them really about the same,nt';
var fourAgreements = 'You have the right to be you.n
You can only be you when you do your best.';
而在ES6中,我们使用反引号就可以解决了:
var roadPoem = `Then took the other, as just as fair,
And having perhaps the better claim
Because it was grassy and wanted wear,
Though as for that the passing there
Had worn them really about the same,`;
var fourAgreements = `You have the right to be you.
You can only be you when you do your best.`;
4、解构赋值
即当键值对的键和值名字相同时,我们可以写一个就可以了。
5、class类的概念
ES6中增加了类的概念,其实ES5中已经可以实现类的功能了,只不过使用Class实现可以更加清晰,更像面向对象的写法。
class Animal {
constructor(){
console.log('我是一个动物');
}
}
class Person extends Animal {
constructor(){
super();
console.log('我是一个程序员');
}
}
let aa = new Person();
//我是一个动物
//我是一个程序员
ES6 新语法
1、箭头函数
ES6中可以使用 => 作为函数表达形式,极简风格,参数+ => +函数体。
如:
var foo = function(){return 1;};
//等价于
let foo = () => 1;
值得注意的是,箭头函数的this的指向的问题,它不是指向window而是指向对象本身
function aa(){
this.bb = 1;
setTimeout(() => {
this.bb++; //this指向aa
console.log(this.bb);
},500);
}
aa(); //2
2、let和const声明变量
在JS中,是没有块级作用域的概念的,而let可以起到这一效果。如,在花括号里声明只在花括号里有效;
{
let a = 1;
var b = 2;
}
console.log(b); // 2
console.log(a); // a is not defind
在JS中变量和函数的声明会提升到当前作用域最顶部执行,这样会出现问题,如在for循环时;
var a = [];
//函数和变量i会最先进行声明,同时全局变量i经过for循环赋值为10
for (var i = 0; i < 10; i++) {
a[i] = function () {
console.log(i);
};
}
console.log(i);//10
a[6]();//10
而let则不会:
for (let i = 0; i < 10; i++) {
a[i] = function () {
console.log(i);
};
}
a[6](); //6
let也不会有变量提升:
console.log(a); // a is not defined
let a = 1;
let也不会允许在同一块级作用域中声明两个同名变量,声明会报错。
const(constant 常数的意思)
const也是用来声明一个变量,并且声明的为一个常量,声明之后不能修改。和let一样,只能在一个块级作用域中声明一个同名变量,且只在这个块级作业域中有效。
const PI = 3.1415;
console.log(PI); // 3.1415
//PI = 3; // Assignment to constant variable.(不能给常量赋值)
//const PI = 3.1;// Identifier 'PI' has already been declared