CoffeeScript中的对象文字多重赋值

我在Javascript中是一个新手。 我正在通过一些Coffeescript代码来查看Atom包,我偶然发现了这段代码:

loadProperties: -> @properties = {} fs.readFile path.resolve(__dirname, '..', 'completions.json'), (error, content) => {@pseudoSelectors, @properties, @tags} = JSON.parse(content) unless error? return 

我最后一行{@pseudoSelectors, @properties, @tags} = JSON.parse(content) unless error?有点困惑, {@pseudoSelectors, @properties, @tags} = JSON.parse(content) unless error? 因为它好像从分析的JSON内容中分配了多个值。 在我的困惑中,我决定使用js2Coffee将其转换回Javascript,最后我得到了以下结果:

 function() { this.properties = {}; // make list of properties (global to provider) return fs.readFile(path.resolve(__dirname, '..', 'completions.json'), (function(_this) { //load completions.json (using path module) return function(error, content) { // edit: nvm, js2coffee's fault. not sure why they wrapped the call back in another anonymous function, but this is a node stream callback var ref; if (error == null) { // if there are no errors ref = JSON.parse(content), _this.pseudoSelectors = ref.pseudoSelectors, _this.properties = ref.properties, _this.tags = ref.tags; } }; })(this)); 

这段代码比上面更容易理解。 我可以看到ref被分配了从内容stream中parsing出来的对象,然后被用来指定其他variables与他们指定的数据。 我的问题是,这种types的任务是如何工作的? 在Coffeescript中,预处理器如何知道在哪里分配值,以及以何种顺序分配它们?

通过检查completions.json,数据不是按照分配的顺序进行的。

这被称为解构分配 。

为了从复杂数组和对象中提取更加方便的值,CoffeeScript实现了ECMAScript Harmony提出的解构赋值语法。 当您将数组或对象字面量赋值给某个值时,CoffeeScript将分解并匹配两边,将右侧的值分配给左侧的variables。

CoffeeScript将=左边的一个对象或数组解释为一个模式,匹配所使用的名称…

  • @pseudoSelectors
  • @properties
  • @tags

…指定的价值范围内的财产或指数:

  • JSON.parse(content).pseudoSelectors
  • JSON.parse(content).properties
  • JSON.parse(content).tags

(定义额外的ref以避免重新评估每个JSON.parse(content) 。)

至于订单,CoffeeScript通常会使用他们在作业中提到的顺序。 将@pseudoSelectors移动到模式中的第三个属性将会在生成的JavaScript中回显。

 {@properties, @tags, @pseudoSelectors} = JSON.parse(content) unless error? 
 var ref; if (typeof error === "undefined" || error === null) { ref = JSON.parse(content), this.properties = ref.properties, this.tags = ref.tags, this.pseudoSelectors = ref.pseudoSelectors; // now last } 

尽pipeJavaScript ObjectJSON.parse(content)的结果一样,并不是作为有序的数据结构来实施的。 如果你需要确保值的顺序,你将不得不使用一个Array