ECMAScript 提案使用小记

Any application that can be written in JavaScript, will eventually be written in JavaScript. — Atwood's Lawjavascript

1. optional chaining

前端一个常见的编程模式是使用短路检查来获取具备 tree 结构的值/方法。例如:html

// 获取 list 对象
res && res.data && res.data.list
// 调用 sendBeacon 方法
navigator.sendBeacon && navigator.sendBeacon('/log', analyticsData())
复制代码

为了处理 deep tree 结构,咱们不得不经过逐层去判断,在代码简洁性和编程模式上大打折扣,作了太多 Repeat 的工做,因此就有了 optional chaining 这个提案,但在其余语言不是个新东西,相似SwiftC#已实现相似的功能了。前端

语法

obj?.prop // 访问静态可选属性 optional static property access
obj?.[expr] // 访问动态可选属性 optional dynamic property access
func?.(...args) // 访问可选函数
复制代码

由此,开始的例子就能够这么写:java

// 获取 list 对象
res?.data?.list
// 调用 sendBeacon 方法
navigator?.sendBeacon('/log', analyticsData())
复制代码

目前这个提案位于 Stage 2 阶段,很大几率会归入正式规范,能够配合 Babel 插件 @babel/plugin-proposal-optional-chaining 进行食用。git

具体技术细节请参考 tc39/proposal-optional-chaininggithub

2. nullish coalescing

另外一个常见的编程模式上在获取具备 tree 结构的属性上,使用 || 操做符来设定默认值。例如:编程

const list = res.data.list || []
复制代码

既当 || 左边的值为 falsy 时,返回右边的默认值,对于值为 undefinednull 这样 falsy 值是没问题的,但在某些场景下, 0''false 是程序所指望的 falsy 值,不该该拿到默认值,因此就有了 nullish coalescing 的提案,解决有意义的 falsy 值被忽略的问题。swift

语法

falsyValue ?? 'default value'
复制代码

使用上,只对于 undefinednull 获取默认值:api

const undefinedValue = response.settings.undefinedValue ?? 'some other default' // result: 'some other default'
const nullValue = response.settings.nullValue ?? 'some other default' // result: 'some other default'
const headerText = response.settings.headerText ?? 'Hello, world!' // result: ''
const animationDuration = response.settings.animationDuration ?? 300 // result: 0
const showSplashScreen = response.settings.showSplashScreen ?? true // result: false
复制代码

这个提案一样位于 Stage 2,可配合 @babel/plugin-proposal-nullish-coalescing-operator 进行食用。babel

具体技术细节请参考 [tc39/proposal-nullish-coalescing](github.com/tc39/propos…)

3. pipeline operator

管道操做符在 Unix 操做系统、F#、julia, 都有相应的实现,其目标是简化函数调用过程,增长代码的可读性:

语法

someValue |> fn1 [|fn2 |fn2...]
复制代码

例如,想要将字符串复制一次+首字母大写+追加 !号,咱们能够有这几个函数:

function doubleSay(str) {
  return str + ', ' + str
}
function capitalize(str) {
  return str[0].toUpperCase() + str.substring(1)
}
function exclaim(str) {
  return str + '!'
}
复制代码

在这以前,可经过函数嵌套调用:

let result = exclaim(capitalize(doubleSay('hello')))
result //=> "Hello, hello!"
复制代码

而使用了管道操做符:

let result = 'hello' |> doubleSay |> capitalize |> exclaim
result //=> "Hello, hello!"
复制代码

目前这个提案位于 Stage 1 阶段,缘由是争议比较大, 食用的话请配合@babel/plugin-proposal-pipeline-operator

参考:tc39/proposal-pipeline-operator

EOF

提案是为了建设功能更日臻完善的 ES 而准备的,具备举足长远的意义,感兴趣的小伙伴可关注官方仓库 追踪最新动态。;)

以上。

相关文章
相关标签/搜索