CoffeeScript 解构赋值
CoffeeScript 实现 ECMAScript Harmony 的提议 解构赋值 语法, 这样从复杂的数组和对象展开数据会更方便一些. 当你把数组或者对象的字面量赋值到一个变量时, CoffeeScript 把等式两边都解开配对, 把右边的值赋值给左边的变量. 最简单的例子, 可以用来并行赋值:
CoffeeScript:编译成JS:
- theBait = 1000
- theSwitch = 0
- [theBait, theSwitch] = [theSwitch, theBait]
- var theBait, theSwitch, _ref;
- theBait = 1000;
- theSwitch = 0;
- _ref = [theSwitch, theBait], theBait = _ref[0], theSwitch = _ref[1];
用来处理函数多返回值也很方便。
CoffeeScript:编译成JS:
- weatherReport = (location) ->
- # 发起一个 Ajax 请求获取天气...
- [location, 72, "Mostly Sunny"]
- [city, temp, forecast] = weatherReport "Berkeley, CA"
- var city, forecast, temp, weatherReport, _ref;
- weatherReport = function(location) {
- return [location, 72, "Mostly Sunny"];
- };
- _ref = weatherReport("Berkeley, CA"), city = _ref[0], temp = _ref[1], forecast = _ref[2];
解构赋值可以用在深度嵌套的数组跟对象上, 取出深度嵌套的属性。
CoffeeScript:编译成JS:
- futurists =
- sculptor: "Umberto Boccioni"
- painter: "Vladimir Burliuk"
- poet:
- name: "F.T. Marinetti"
- address: [
- "Via Roma 42R"
- "Bellagio, Italy 22021"
- ]
- {poet: {name, address: [street, city]}} = futurists
- var city, futurists, name, street, _ref, _ref1;
- futurists = {
- sculptor: "Umberto Boccioni",
- painter: "Vladimir Burliuk",
- poet: {
- name: "F.T. Marinetti",
- address: ["Via Roma 42R", "Bellagio, Italy 22021"]
- }
- };
- _ref = futurists.poet, name = _ref.name, (_ref1 = _ref.address, street = _ref1[0], city = _ref1[1]);
解构赋值还可以跟 splats 搭配使用。
CoffeeScript:编译成JS:
- tag = "
" [open, contents..., close] = tag.split("")
- var close, contents, open, tag, _i, _ref,
- __slice = [].slice;
- tag = "
"; _ref = tag.split(""), open = _ref[0], contents = 3 <= _ref.length ? __slice.call(_ref, 1, _i = _ref.length - 1) : (_i = 1, []), close = _ref[_i++];
展开式(expansion)可以用于获取数组结尾的元素, 而不需要对中间过程的数据进行赋值. 它也可以用在函数参数的列表上。
CoffeeScript:编译成JS:
- text = "Every literary critic believes he will
- outwit history and have the last word"
- [first, ..., last] = text.split " "
- var first, last, text, _ref;
- text = "Every literary critic believes he will outwit history and have the last word";
- _ref = text.split(" "), first = _ref[0], last = _ref[_ref.length - 1];
解构赋值也可以用在 class 的构造器上, 从构造器配置对象赋值到示例属性上。
CoffeeScript:编译成JS:
- class Person
- constructor: (options) ->
- {@name, @age, @height} = options
- tim = new Person age: 4
- var Person, tim;
- Person = (function() {
- function Person(options) {
- this.name = options.name, this.age = options.age, this.height = options.height;
- }
- return Person;
- })();
- tim = new Person({
- age: 4
- });
转载本站内容时,请务必注明来自W3xue,违者必究。