Javascript 将类转换为函数
我正在制作一个实时应用程序,想把这个Javascript 将类转换为函数,javascript,class,momentjs,feathersjs,Javascript,Class,Momentjs,Feathersjs,我正在制作一个实时应用程序,想把这个类代码转换成函数 下面的函数是否等效?从任何人都能看到的情况来看,将它保持为类而不是函数会有好处吗 class IdeaService { constructor() { this.ideas = []; } async find() { return this.ideas; } async create(data) { const idea = { id: this.ideas.length,
类
代码转换成函数
下面的函数是否等效?从任何人都能看到的情况来看,将它保持为类而不是函数会有好处吗
class IdeaService {
constructor() {
this.ideas = [];
}
async find() {
return this.ideas;
}
async create(data) {
const idea = {
id: this.ideas.length,
text: data.text,
tech: data.tech,
viewer: data.viewer
};
idea.time = moment().format('h:mm:ss a');
this.ideas.push(idea);
return idea;
}
}
功能
function ideaService() {
let ideas = [];
async find() {
return ideas;
}
async create(data) {
const idea = {
id: ideas.length,
text: data.text,
tech: data.tech,
viewer: data.viewer
}
idea.time = moment().formate('h:mm:ss a');
ideas.push(idea);
return idea;
}
}
试试这个
let IdeaService = (function() {
let ideas = [];
async function find() {
return ideas;
}
async function create(data) {
const idea = {
id: ideas.length,
text: data.text,
tech: data.tech,
viewer: data.viewer
};
idea.time = moment().format('h:mm:ss a');
ideas.push(idea);
return idea;
}
return {
find,
create
}
})();
编辑!如果您不希望在运行此文件时实例化此模块,请删除();最后。因此,功能将是:
IdeaService = (function() {
});
let ideaService = IdeaService();
举例来说:
IdeaService = (function() {
});
let ideaService = IdeaService();
“从大家看到的情况来看,将其保留为类而不是函数会有好处吗?”如果不知道是否需要,为什么要将该类转换为函数?函数版本是语法错误,您可以通过尝试来发现,因此,我想继续工作将是保持它为类的好处。@VLAZ我宁愿不必担心
这个
和中的类语法general@and1如果要将对象与方法一起使用,则无论使用何种语法,都必须“担心此问题”(即了解如何使用它)。