【发布时间】:2015-08-25 02:04:28
【问题描述】:
我是 Javascript 的新手。我正在查看 Atom 包的一些 Coffeescript 代码,我偶然发现了这段代码:
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? 有点困惑,因为它似乎从解析的 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,数据不是按分配发生的顺序。
【问题讨论】:
-
哈哈我一直在尝试为此类对象找到正确的术语。来自 Ruby 背景,我倾向于称它们为哈希,这是不正确的。谢谢(你的)信息。 @FelixKling
-
它们在 JavaScript 中被称为“对象”。如果你称他们为“哈希”,人们就会明白你的意思(并且可能不会抱怨太多)。
-
我会抱怨的。 ;-) 对于 OP,有些人所谓的“JSON 对象”是 Object initialiser,也称为 object literal。 JSON 使用这种语法作为其符号,因此会造成混淆。
标签: javascript json node.js coffeescript