实用的ES6特性

1. 函数参数默认值

不使用ES6

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

function foo(height, color)
{
    var height = height || 50;
    var color = color || 'red';
    //...
}

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

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

使用ES6

function foo(height = 50, color = 'red')
{
    // ...
}

2. 模板字符串

不使用ES6

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

var name = 'Your name is ' + first + ' ' + last + '.' 

使用ES6

将变量放在大括号之中:

var name = `Your name is ${first} ${last}.`;

ES6的写法更加简洁、直观。

3. 多行字符串

不使用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,`

4. 解构赋值

不使用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');

5. 对象属性简写

不使用ES6

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

var bar = 'bar';
var foo = function ()
{
    // ...
}
var baz = {
  bar: bar,
  foo: foo
};

使用ES6

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

var bar = 'bar';
var foo = function ()
{
    // ...
}
var baz = { bar, foo };

  

 

 

 

posted @ 2018-04-02 14:11  Sugеr  阅读(161)  评论(0)    收藏  举报