首页 > 语言 > JavaScript > 正文

前端开发不得不知的10个最佳ES6特性

2024-05-06 15:12:04
字体:
来源:转载
供稿:网友

为了保证可读性,本文采用意译而非直译,并且对源代码进行了大量修改。另外,本文版权归原作者所有,翻译仅用于学习。

ES6,正式名称是ECMAScript2015,但是ES6这个名称更加简洁。ES6已经不再是JavaScript最新的标准,但是它已经广泛用于编程实践中。如果你还没用过ES6,现在还不算太晚…

下面是10个ES6最佳特性,排名不分先后:

函数参数默认值 模板字符串 多行字符串 解构赋值 对象属性简写 箭头函数 Promise Let与Const 类 模块化 函数参数默认值 不使用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'){ // ...}

模板字符串

不使用ES6

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

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

使用ES6

将变量放在大括号之中:

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

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

多行字符串

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

解构赋值

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

对象属性简写

不使用ES6

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

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

使用ES6

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

var bar = 'bar';var foo = function (){ // ...}var baz = { bar, foo };            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选