es6 语法新特性

1,const let 关键字

// 在javascript中变量默认是全局的,只存在函数级作用域,没有块级作用域。let定义块级作用域:
if(true){
    let a = 'name';
}
// const用来定义一个常量,一旦定义不可修改,如果是应用类型的,可以改变属性:
const name = 'hello';
name = 'happy';     # 报错
const name = {foo:'hello'};
name.foo = 'happy';

2,箭头函数

// 一种声明函数的方式,匿名
let add = (a, b) => {return a + b;}
// 当后面是表达式(expression)的时候,还可以简写成
let add = (a, b) => a + b;
// 等同于
let add = function(a, b) {
    return a + b;
}
// 在回调函数中应用
let numbers = [1, 2, 3];
let doubleNumbers = numbers.map((number) => number * 2);
console.log(doubleNumbers)
// [2, 4, 6] 

3,this

// 原js中setTimeout中的this是全局this
let kitty = {
    age: 1,
    grow: function(){
        setTimeout(() =>{
            console.log(this.age);
        }, 100);
    }
}

4,函数默认参数

// 原js中默认参数 values = values || []
function desc(name = 'Peter', age = 5){
    return name + ' is ' + age + 'years old';
}
desc();
// Peter is 5 years old

5,rest参数/展开操作符

// 当一个函数的最后一个参数有“...”这样的前缀,是一个有参数的数组
function test(...args){
    console.log(args);
}
test(1, 2, 3);
// [1, 2, 3]
// 它和普通参数的区别:rest参数只是没有指定变量名称的参数数组,可以使用sort,map等方法。

// 展开操作符用于函数掉用
function test(x, y, z){};
let args = [0, 1, 2];
test(...args);

// 展开操作符用于数组字面量
let arr1 = [1, 2];
let arr2 = [3, 4];
let arr3 = [...arr1, ...arr2];
console.log(arr3);
// 1, 2, 3, 4

// 展开操作符用于对象,将 Rest 解构赋值 / 扩展运算符( ... )引入对象。 Babel 转码器已经支持这项功能
let a = {x: 1};
let b = {y: 2, ...a};
console.log(b);
// {x:1, y:2}

6,模板字符串

// 原js中 var a = 'hh' + 'hh'; 换行必须用 +
let a = `hhhh`;
// 代码中所用不是引号

7,解构赋值

// 解构数组
let foo = ['one', 'two', 'three'];
let [a, b, c] = foo;
console.log(`$(a), $(b), $(c)`;
// one, two, three

// 解构对象
let person = {name: 'viking', age: 20};
let {name, age} = person;
console.log('`$(name), $(age)')
// viking, 20

8,类

// 原js中使用原型链的方式来完成继承,即:
function Point(x, y){
    this.x = x;
    this.y = y;
}
Point.prototype.toString = function(){
    return `( ${this.x} , ${this.y} )`
}
var p = new Point(1,2);
p.toString();
// (1, 2)

// 定义类 
class Point { 
    constructor (x, y) { 
        this.x =x; 
        this.y =y; 
    } 
    toString () { 
        return `( ${this.x}, ${this.y} )`; 
    } 
    toValue () { 
        return this.x+this.y;
    } 
} 
var p = new Point(1,2); 
p.toString(); 
//"(1,2)" 
p.toValue(); 
//3

// constructor方法是类的默认方法,通过new 命令生成对象实例时,自动调用该方法,一个类必须有constructor方法,如果没有显示定义,一个空的constructor方法会被默认添加

// 继承
class Foo { 
    static classMethod() { 
        return 'hello'; 
    } 
} 
class Bar extends Foo { 

} 
Bar.classMethod() 
// 'hello

9,模块

// helllo.js文件
function a(){
    console.log('hello es6');
}

// 使用export导出模块
export a;
export const p = 3.14;
// 使用default关键字导出模块
export default function(){
    console.log('hello');
}

// main.js
// 加载一个模块
import {a} from './hello';
// 使用*全部导出
import * as fun from './hello';
// 使用对象解构赋值加载2个变量
import {p,a} from './hello';

a();
// hello es6

猜你喜欢

转载自blog.csdn.net/qq_35790269/article/details/81672482