Javascript CoffeeScript中的对象文字多重赋值
我对Javascript有点生疏。我在浏览Atom软件包的一些Coffeescript代码时,偶然发现了以下代码:Javascript CoffeeScript中的对象文字多重赋值,javascript,json,node.js,coffeescript,Javascript,Json,Node.js,Coffeescript,我对Javascript有点生疏。我在浏览Atom软件包的一些Coffeescript代码时,偶然发现了以下代码: loadProperties: -> @properties = {} fs.readFile path.resolve(__dirname, '..', 'completions.json'), (error, content) => {@pseudoSelectors, @properties, @tags} = JSON.parse(c
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),我有点困惑,除非出现错误?
,因为它似乎从解析的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被分配了从内容流解析的对象,然后被用来分配其他变量及其指定的数据。我的问题是,这种类型的任务是如何工作的?在Coffeescript中,预处理器如何知道在何处分配值,以及以何种顺序分配值
通过检查completions.json,数据不符合分配发生的顺序。这称为
为了更方便地从复杂数组和对象中提取值,CoffeeScript实现了ECMAScript Harmony提出的语法。当您将数组或对象文字指定给一个值时,CoffeeScript会分解,并将两侧相互匹配,将右侧的值指定给左侧的变量
CoffeeScript将=
左侧的对象或数组解释为模式,与使用的名称匹配
@伪选择器
@properties
@标签
JSON.parse(content).pseudo选择器
JSON.parse(content.properties)
JSON.parse(content.tags)
ref
,以避免对每个JSON.parse(content)
进行重新评估。)
至于顺序,CoffeeScript通常会使用作业中提到的顺序。将@pseudoSelectors
移动到模式中的第三个属性将在生成的JavaScript中得到响应
{@properties, @tags, @pseudoSelectors} = JSON.parse(content) unless error?
不过,与JSON.parse(content)的结果一样,它们并没有作为排序数据结构强制执行。如果需要确保值的顺序,则必须使用
数组
哈哈,我一直在尝试为此类对象找到正确的术语。来自Ruby背景,我倾向于称之为哈希,这是不正确的。谢谢你的信息@FelixKling它们在JavaScript中被称为“对象”。如果你叫他们“哈什”,人们就会明白你的意思(而且可能不会抱怨太多)。我会抱怨的对于OP,有人所谓的“JSON对象”是一个对象,也称为对象文本。JSON使用这种语法作为它的符号,因此产生了混乱。太棒了,这正是我想要的。非常感谢!
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
}