ES6 函数参数的 destructuring

发布时间: 2017-06-20 14:20:03 作者: 大象笔记

在 weex 中使用 vuex 的 actions 时,发现了 ES6 的一种新语法

export function FETCH_USER ({ commit, state }, { id }) {
  return state.users[id]
    ? Promise.resolve(state.users[id])
    : fetchUser(id).then(user => commit('SET_USER', { user }))
}

之前从未见过函数可以这样定义, 参数居然都是 object。查了一下,发现是 ES6 的新特性

函数参数 destructuring - 即,解构赋值

写了一个 demo 测试一下

function hello(frameworks) {
	console.log("hello " + frameworks.f1);
	console.log("hello " + frameworks.f2);
}

function hello2({f1, f2}) {
	console.log("hello " + f1);
	console.log("hello " + f2);
}

console.log("ES5");
hello({f1: 'vuejs', f2: 'weex'});
console.log("ES6");
hello2({f1: 'vuejs', f2: 'weex'});

node 下的运行结果

$ node fun.js
ES5
hello vuejs
hello weex
ES6
hello vuejs
hello weex

函参 destructuring 的好处

首先,可读性大大提高,否则,没有注释的情况下,需要阅读代码才知道具体的参数解构。 文档中提到的其他好处,暂时没有实际体会到。

参考

我是一名山东烟台的开发者,联系作者