最新一期ES6特性,你值得了解!!!

ES6的常用最佳特性及扩展


 ES6(ECMAScript2015)的出现,无疑给前端开发人员带来了新的惊喜,它包含了一些很棒的新特性,可以更加方便的实现很多复杂的操作,提高开发人员的效率。 本文主要针对ES6做一个简要介绍。 主要译自:webapplog.com/ES6/comment…。也许你还不知道ES6是什么, 实际上, 它是一种新的javascript规范。在这个大家都很忙碌的时代,如果你想对ES6有一个快速的了解,那么请继续往下读,去了解当今最流行的编程语言JavaScript最新一代的常用特性。

下面是诸多ES6常用最佳特性,排名不分先后:

    1. 函数参数默认值 (Default Parameters)
    1. 模板字符串 (Template Literals )
    1. 块作用域构造Let与Const (Block-Scoped Constructs Let and Const)
    1. 箭头函数 (Arrow Functions)
    1. 多行字符串 (Multi-line Strings)
    1. 解构赋值 (Destructuring Assignment )
    1. 对象属性简写 (Enhanced Object Literals)
    1. Promise
    1. 类 (Classes)
  • 10.模块化 (Modules)
  • 11.ES6扩展

1. 函数参数默认值 (Default Parameters)

不使用ES6

为函数的参数设置默认值:

function f(height, color)
{
    var height = height || 50;
    var color = color || 'red';
    //...
}
复制代码

这样写一般没问题,但是,当参数的布尔值为false时,是会出事情的!比如,我们这样调用f函数:

f(0, "", "")
复制代码

因为0的布尔值为false,这样height的取值将是50。同理color的取值为‘red’。

使用ES6

function f(height = 50, color = 'red'){
    // ...
}
复制代码

2. 模板字符串 (Template Literals )

不使用ES6

使用+号将变量拼接为字符串:

var name = 'Your name is ' + first + ' ' + last + '.'
复制代码

使用ES6

将变量放在大括号之中:

var name = `Your name is ${first} ${last}.`
复制代码

3. 块作用域构造Let与Const (Block-Scoped Constructs Let and Const)

使用Var

var定义的变量为函数级作用域:

{
  var a = 10;
}
console.log(a); // 输出10
复制代码

使用let与const

let定义的变量为块级作用域,因此会报错

{
  let a = 10;
}
console.log(a); // 报错“ReferenceError: a is not defined”
复制代码

谈到const,它就是一个不变量,也是块级作用域就像let一样


4. 箭头函数 (Arrow Functions)

不使用ES6

普通函数体的this,指向调用时所在的对象

function f() 
{
    console.log(this.id);
}
var id = 1;
f(); // 输出1
f.call({ id: 2 }); // 输出2
复制代码

使用ES6

箭头函数体内的this,就是定义时所在的对象,而不是调用时所在的对象。

var f = () => {
  console.log(this.id);
}
var id = 1;
f(); // 输出1
f.call({ id: 2 }); // 输出1
复制代码

5. 多行字符串 (Multi-line Strings)

不使用ES6

使用“\n\t”将多行字符串拼接起来:

var roadPoem = 'Then took the other, as just as fair,\n\t'
    + 'And having perhaps the better claim\n\t'
    + 'Because it was grassy and wanted wear,\n\t'
    + 'Though as for that the passing there\n\t'
    + 'Had worn them really about the same,\n\t'
复制代码

使用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,`
复制代码

6. 解构赋值 (Destructuring Assignment )

不使用ES6

当需要获取某个对象的属性值时,需要单独获取:

var data = $('body').data(); // data有house和mouse属性
var house = data.house;
var mouse = data.mouse;
复制代码

使用ES6

一次性获取对象的子属性:

var { house, mouse} = $('body').data()
复制代码

对于数组也是一样的:

var [col1, col2]  = $('.column');
复制代码

7. 对象属性简写 (Enhanced Object Literals)

不使用ES6

对象中必须包含属性和值,显得非常多余:

var bar = 'bar';
var f = function ()
{
    // ...
}
var baz = {
  bar: bar,
  f: f
};
复制代码

使用ES6

对象中直接写变量,非常简单:

var bar = 'bar';
var f = function ()
{
    // ...
}
var baz = { bar, f };
复制代码

8. Promise

不使用ES6

嵌套两个setTimeout回调函数:

setTimeout(function()
{
    console.log('Hello'); // 1秒后输出"Hello"
    setTimeout(function()
    {
        console.log('World'); // 2秒后输出"World"
    }, 1000);
}, 1000);
复制代码

使用ES6

使用两个then是异步编程串行化,避免了回调:

var wait1000 = new Promise(function(resolve, reject)
{
    setTimeout(resolve, 1000);
});

wait1000
    .then(function()
    {
        console.log("Hello"); // 1秒后输出"Hello"
        return wait1000;
    })
    .then(function()
    {
        console.log("World"); // 2秒后输出"World"
    });
复制代码

9. 类 (Classes)

不使用ES6

使用构造函数创建对象:

function Point(x, y)
{
    this.x = x;
    this.y = y;
    this.add = function()
    {
        return this.x + this.y;
    };
}
var p = new Point(1, 2);
console.log(p.add()); // 输出3
复制代码

使用ES6

使用Class定义类,更加规范,且你能够继承:

class Point
{
    constructor(x, y)
    {
        this.x = x;
        this.y = y;
    }
    add()
    {
        return this.x + this.y;
    }
}
var p = new Point(1, 2);
console.log(p.add()); // 输出3
复制代码

10.模块化 (Modules)

JavaScript一直没有官方的模块化解决方案,开发者在实践中主要采用CommonJS和AMD规范。而ES6制定了模块(Module)功能

不使用ES6

Node.js采用CommenJS规范实现了模块化,而前端也可以采用,只是在部署时需要使用Browserify等工具打包。这里不妨介绍一下CommenJS规范。

module.js中使用module.exports导出port变量和getAccounts函数:

module.exports = {
  port: 3000,
  getAccounts: function() {
    ...
  }
}
复制代码

main.js中使用require导入module.js:

var service = require('module.js')
console.log(service.port) // 输出3000
复制代码

使用ES6

ES6中使用export与import关键词实现模块化。

module.js中使用export导出port变量和getAccounts函数:

export var port = 3000
export function getAccounts(url) {
  ...
}
复制代码

main.js中使用import导入module.js,可以指定需要导入的变量:

import {port, getAccounts} from 'module'
console.log(port) // 输出3000
复制代码

也可以将全部变量导入:

import * as service from 'module'
console.log(service.port) // 3000
复制代码

11.ES6扩展

1. 严格模式

之前学习的JS,语法非常灵活,JS中这个灵活的特性,弊大于先利。后来增加了严格模式。使用严格模式的目的:规则,提高编译效率。

怎么去启动严格模式: "use strict"

严格模式和非严格模式有什么区别: (1)在严格模式下不能使用没有var的变量

"use strict";
 a = 110//报错
复制代码

(2)在严格模式下不能8进制的数字

"use strict"var a = 01;
//报错
复制代码

(3)在严格模式下不能把函数定义在if语句中

;;'"use strict";
 if(true){
     function f(){
         console.log("f..")
     }
 }//报错
复制代码

(4)在严格模式下函数不能有重名的形参

"use strict"function f(a,a){
         console.log("f..")
     }//报错
复制代码

(5)在严格模式下不能arguments就不能使用了

"use strict"function f(a,b){
         console.log(a, b)
         console.log(arguments[0], arguments[1])
         arguments[0] = 1111;
         arguments[1] = 2222;
         console.log(a, b)
         console.log(arguments[0], arguments[1])
     }
     f(1, 2)//输出 1 2,1 2,1 2 ,1111 2222
复制代码

(6)在严格模式下不能function中的this就再在是window

2. 新的两种数据结构(集合)

  • (1)set
  • set和数组差不多,也是一种集合,区别在于:它里面的值都是唯一的,没有重复的。
  • set不是数组,是一个像对象的数组,是一个伪数组
  • set可以用forEach,for of 遍历
  • (2)map
  • 它类似于对象,里面存放也是键值对,区别在于:对象中的键名只能是字符串,如果使用map,它里面的键可以是任意值

3. 字符串扩展

  • (1)模板字符串  见上文...
  • (2)trim
  • 除去字符串空格的。
  • trim 左右空格都是去掉
  • trimLeft 左空格去掉
  • trimRight 右空格去掉

一般配合正则表达式,用的比较的。

var str = "a ab abc " 
复制代码
  • (3)repeat
 var str = "123456789"
 console.log(str.repeat(20))//重复输出20次
复制代码
  • (4)includes  判断一个字符串里是否包含某个元素
  • (5)startwith  判断一个字符串里是否以某个元素开始
  • (6)endwith  判断一个字符串里是否以某个元素结束
  • (7)padStart  在字符串的头部插入新的元素
  • (8)padEnd  在字符串的尾部插入新的元素

4. 数组扩展

ES6中新增的方法

  • Array.from
  • arguments&getElementsByTabName() : 伪数组
  • Array.of :创建一个数组
  • find()
  • findIndex()
  • includes
  • fill
  • 数组的扩展运算符

另外

这里还有许多ES6的其它特性你可能会使用到,排名不分先后:

  • 1、全新的Math, Number, String, Array 和 Object 方法
  • 2、Symbols符号
  • 3、tail调用
  • 4、Generators (生成器)

参考文献

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值