es6的语法糖虽然很方便,但是目前浏览器大多不支持es6的语法,需要使用bable进行转换。
新特性如下:
1、可以通过class关键字创建类,通过extends关键字继承类
//父类
class Human {
constructor(name) {
this.name = name;
}
breathe() {
console.log(this.name + " is breathing");
}
}
//子类
class Man extends Human {
constructor(name, sex) {
super(name);
this.sex = sex;
}
info(){
console.log(this.name + 'is ' + this.sex);
}
}
var xx = new Man('jarson', 'boy');
xx.breathe(); //jarson is breathing
xx.info(); //arsonis boy
对比之前创建类的方式(用functio创建、用prototype继承)
function Human(name) {
this.name = name;
this.breathe = function() {
console.log(this.name + ' is breathing');
}
}
var man = new Human('jarson');
man.breathe();
2、增加了模块的使用:将不同功能的代码分别写在不同文件中,各模块只需导出(export)
公共接口部分,然后在需要使用的地方通过模块的导入(import)
就可以了。
1)模块导出:export
//导出单个模块
export class Human{
constructor(name) {
this.name = name;
}
breathe() {
console.log(this.name + " is breathing");
}
}
//导出一组对象
function run(){
console.log('i am runing');
}
export {Human, run};
//default导出:default关键字在每一个模块中只能使用一次。
export default { //把Human类和run函数标注为default对象导出。
Human,
run
};
2)模块导入:import
如果模块包含一些逻辑要执行,且不会导出任何对象,此类对象也可以被导入到另一模块中,导入之后只执行逻辑。
//导入默认对象
import './module1.js';
//使用Default导出方式导出对象,该对象在import声明中将直接被分配给某个引用,如下例中的“app”
import app from './module1.js';
//若导出了一组对象,则应该在导入声明中一一列出这些对象
import {Human, run} from './app.js'
3、变量声明方式:增加了let和const
在定义变量的时候统统使用let
来代替var;const用来定义常量。
4、箭头函数:=>
左边为输入的参数,而右边则是进行的操作以及返回的值
let arr = [6, 8, 10, 20, 15, 9];
arr.forEach((item, i) => console.log(item, i));
5、字符串模板:ES6中允许使用反引号 ` 来创建字符串,此种方法创建的字符串里面可以包含由美元符号加花括号包裹的变量${vraible}。
//产生一个随机数
let num = Math.random();
//将这个数字输出到console
console.log(`your num is ${num}`);
6、解构:若一个函数要返回多个值,常规的做法是返回一个对象,将每个值做为这个对象的属性返回。在ES6中,利用解构这一特性,可以直接返回一个数组,然后数组中的值会自动被解析到对应接收该值的变量中。
function getVal() {
return [1, 2];
}
var [x,y] = getVal(); //函数返回值的解构
7、 默认参数:现在可以在定义函数的时候指定参数的默认值了,而不用像以前那样通过逻辑或操作符来达到目的了。
//es6写法:ame指定默认参数
function sayHello2(name='tom'){ //如果没有传这个参数,才会有默认值,
console.log(`Hello ${name}`);
}
//传统写法
function sayHello(name){
var name=name||'tom'; //传统的指定默认参数的方式
console.log('Hello '+name);
}
8、Promise
let promise = new Promise ( (resolve, reject) => {
if ( success ) {
resolve(a) // pending ——> resolved 参数将传递给对应的回调方法
} else {
reject(err) // pending ——> rejectd
}
} )