javascript - 无法从 JS 中的简单模块调用方法
问题描述
我试图通过使用 getPosts 函数在调用时返回它来从我的模块(Tweeter)中传递一个数组(_posts)。
当我尝试打印/传递它时 - 它只是打印函数的代码而不是返回数组。
const Tweeter = function() {
const _posts = [{
text: "First post!",
id: "p1",
comments: [{
id: "c1",
text: "First comment on first post!"
},
{
id: "c2",
text: "Second comment on first post!!"
},
{
id: "c3",
text: "Third comment on first post!!!"
}
]
},
{
text: "Aw man, I wanted to be first",
id: "p2",
comments: [{
id: "c4",
text: "Don't wory second poster, you'll be first one day."
},
{
id: "c5",
text: "Yeah, believe in yourself!"
},
{
id: "c6",
text: "Haha second place what a joke."
}
]
}
]
const getPosts = function() {
return _posts
}
return {
getPosts: getPosts
}
}
解决方案
定义完成后,需要新建一个 Tweeter 对象,比如
const tweets = new Tweeter();
// now you can do
tweets.getPosts();
或者您可以简单地调用您的函数定义,例如:
const Tweeter = function() {
const _posts = [{
text: "First post!",
id: "p1",
comments: [{
id: "c1",
text: "First comment on first post!"
},
{
id: "c2",
text: "Second comment on first post!!"
},
{
id: "c3",
text: "Third comment on first post!!!"
}
]
},
{
text: "Aw man, I wanted to be first",
id: "p2",
comments: [{
id: "c4",
text: "Don't wory second poster, you'll be first one day."
},
{
id: "c5",
text: "Yeah, believe in yourself!"
},
{
id: "c6",
text: "Haha second place what a joke."
}
]
}
]
const getPosts = function() {
return _posts
}
return {
getPosts: getPosts
}
}();
现在你可以简单地做,Tweeter.getPosts();
如果您要从文件中导出它,您可以简单地执行以下操作:
export const Tweeter = function() {
const _posts = [{
text: "First post!",
id: "p1",
comments: [{
id: "c1",
text: "First comment on first post!"
},
{
id: "c2",
text: "Second comment on first post!!"
},
{
id: "c3",
text: "Third comment on first post!!!"
}
]
},
{
text: "Aw man, I wanted to be first",
id: "p2",
comments: [{
id: "c4",
text: "Don't wory second poster, you'll be first one day."
},
{
id: "c5",
text: "Yeah, believe in yourself!"
},
{
id: "c6",
text: "Haha second place what a joke."
}
]
}
]
const getPosts = function() {
return _posts
}
return {
getPosts: getPosts
}
};
现在您可以导入其他文件,例如:
import {Tweeter} from './tweeter.js';
// use it like
const tweets = new Tweeter();
const posts = tweets.getPosts();
希望能帮助到你。
推荐阅读
- json - 从 JSON 检索值到经典 ASP
- angular - 有没有办法在 Angular 7 中命名路线?
- mysql - UNION ALL LEFT JOIN 和 SUM 返回不正确的值
- selenium - 使用无头时 Selenium 数据目录出错
- java - 合并两个不重复的对象列表
- swift - 如何在 UIViewControllers 之间使用委托?
- python - ndarray 的大小何时不固定?
- html - WordPress Avada - Fusion Main Menu:如何在顶级水平菜单项之间实现居中定位?
- python - TensorFlow 中的块激活函数实现
- ubuntu-16.04 - OPENOCD 烧写 FT2232 芯片