Node 6 几个新特性

    
banq
16-04-28 0 814

Node.js 6.0刚刚发布,带来了Javascript 6新特点,下面是几个令人激动的新特性:

1. Function参数默认值
曾几何时,你编写了很多次如下代码:

function beginTeleportation (who, options) {
 options = options || {}
}

现在检查函数参数是否存在再也没有必要了, Default function parameters 默认函数参数能够让定义函数的默认参数。


function sayCosmicGreeting (greeting = 'Greetings', name = 'Earthling') {
  console.log(`${greeting}, ${name}`)
}

sayCosmicGreeting() // Greetings, Earthling
sayCosmicGreeting('Salutations', 'Martian')
// Salutations, Martian

这里函数参数greeting和name都有自己默认值,所以,如果你没有赋值空参数调用,就会输出默认值Greetings和 Earthling。


2.Rest参数
传递许多参数到函数中需要使用arguments 关键词:

function sayCosmicGreetingTo (greeting) {
  const beings = arguments.slice(1)
  beings.forEach(being => {
    console.log(`${greeting}, ${being}`)
  })
}

sayCosmicGreetingTo('Hello', 'Earthling', 'Martian', 'Neptunian')

上述代码问题会报错:TypeError: arguments.slice is not a function,因为arguments 不是实际数组,只是类似,为了能正常工作,你需要使用数组原型的call函数:
Array.prototype.slice.call(arguments, 1)

但是这些处理手法对于初学者很费解,而Rest parameters解决这个问题,给你一个真正实际的Array数组实例:


function sayCosmicGreetingTo (greeting, ...beings) {
  beings.forEach(being => {
    console.log(`${greeting}, ${being}`)
  })
}

sayCosmicGreetingTo('Hello', 'Earthling', 'Martian', 'Neptunian')


注意到函数参数beings之前有“...”前缀,这个前缀表示这是一个数组,从0到数组最大长度之间的元素值是由实际传入参数决定的。

3.解构
在Javascript中普遍模式是将一个对象作为配置可选项,以前,这些选项得手工从对象中分解出来然后分配给相应变量。


function beginDepartureSequence (options) {
  const captain = options.captain
  const ship = options.ship
  const destination = options.destination
  console.log(`Blast off sequence initiated for Captain ${captain} on ship ${ship} flying to ${destination}`)
}

beginDepartureSequence({
  captain: 'Rey',
  ship: 'Millennium Falcon',
  destination: 'Jakku'
})

现在使用 destructure 可以直接将对象解构到变量,无论顺序:


function beginDepartureSequence (options) {
  const { destination, captain, ship } = options
  console.log(`Blast off sequence initiated for Captain ${captain} on ship ${ship} flying to ${destination}`)
}

beginDepartureSequence({
  captain: 'Rey',
  ship: 'Millennium Falcon',
  destination: 'Jakku'
})


上面options对象被直接解构分配给了变量destination, captain, ship三个,我们可以做得更好,可以直接在函数参数中声明这些变量名:


function beginDepartureSequence ({ destination, ship, captain }) {
  console.log(`Blast off sequence initiated for Captain ${captain} on ship ${ship} flying to ${destination}`)
}

beginDepartureSequence({
  captain: 'Rey',
  ship: 'Millennium Falcon',
  destination: 'Jakku'
})


以上只是简单几个新特点,更多支持Javascript6 或Javascript7的特性可以参考:http://node.green/


原文:
Node 6 Features You Need Know To About