【发布时间】:2016-10-22 00:56:24
【问题描述】:
我将我们的员工保存在一个 json 文件中,并且想到了将这些数据与 ES6 类一起使用。我越是处理这个问题,我就越觉得我可能错过了一些东西。我在咖啡脚本中这样工作:
fetch = require('node-fetch')
domain = 'domain.com'
apiSrc = 'api.domain.com'
slug = 'people'
class Person
constructor: (json) -> {name: @name, title: @title, school: @school, bio: @bio} = json
email: (username) ->
username.replace(/\s/, '.').toLowerCase() + '@' + domain
profile: ->
content = []
if this.name then content.push("#{@name}")
if this.title then content.push("#{@title}")
if this.school then content.push(school) for school in "#{@school}"
if this.bio then content.push("#{@bio}")
if this.name then content.push(this.email("#{@name}"))
content.join('')
fetch('http://' + apiSrc + '/' + slug + '.json')
.then((response) -> response.json())
.then((api) ->
content = []
group = []
group.push(new Person(them)) for them in api[slug]
for them, index in group
content.push(them.profile())
console.log(content.join(''))
)
但后来我想如果我能把它转换成 ES6 会更好。我知道用例很简单,当然也不需要类,因为我只是将数据用于模板,但是,为了学习,我试图这样做。我会以错误的方式解决这个问题吗?现在,我觉得应该有一种方法可以返回我放入 Person 类的所有“人”。但是,我能弄清楚如何做到这一点的唯一方法是运行一个 for 循环,然后将其写入文档。
class Person {
constructor(data) { ({name: this.name, title: this.title, school: this.school, bio: this.bio, email: email(this.name)} = data); }
email(username) {
return username.replace(/\s/, '.').toLowerCase() + '@' + location.hostname.replace(/[^\.\/\@]+\.[^\.\/]+$/, '');
}
profile() {
return `${this.name} ${this.title}`;
}
}
var apiSrc = 'api.domain.com';
var slug = 'people';
fetch(`http://${apiSrc}/${slug}.json`)
.then(function(response) { return response.json() }) // .then(response => response.json())
.then(function(api) {
var content = [];
var group = [];
for (var i = 0; i < api[slug].length; i++) { var them = api[slug][i]; new Person(them); }
for (var i = 0; index < group.length; i++) {
var them = group[i];
content.push(them.profile());
console.log(content.join(''));
}
});
我的 ES6 转换实际上现在甚至无法正常工作。 API 返回 JSON,但之后它就搞砸了。任何建议都会非常有帮助,因为我正在努力提高自己作为编码员的水平,并希望这种示例可以帮助其他人在实际用例中学习类。
【问题讨论】:
-
我不明白您所说的“我觉得应该有一种方法可以返回我放入
Person类中的所有“人” ”。你做得很好,没有(而且应该)没有办法收集一个类的所有实例。您可以返回您放入group数组中的所有人员。这正是它应该如何工作的。 -
由于我没有上课经验,我认为有某种回报,例如(编造这个)
Object.getClassEntries(allthePeople.constructor())。当我返回group并且它工作时,我注意到构造函数似乎对输出没有任何影响。所以我想如果构造函数没有做任何事情,我一定做错了。 -
我不确定您预期的影响。您的 ES6 类与您的 CS 类非常等价(忽略
profile返回值)。您希望有什么不同的行为方式? -
嗯,我不相信我一开始就做对了。如果我这样做了,那么我想我只是在寻找不存在的东西。那么构造函数的意义何在?
-
使用类与直接将 JSON 解析为输出模板相比有什么好处?
标签: javascript json class coffeescript ecmascript-6