javascript - JS类中的函数和静态保留字
问题描述
我已经学习了NodeJS,但是Product类中的_getProductsFromFile函数有一些问题,我认为问题是静态保留字,我得到的错误是
TypeError: this._getProductsFromFile is not a function at Function.fetchAll (/Users/huynhhuukhanh/HKhansh/BE/Learn-NodeJS/refactoring-MVC-pattern/models/product.js:57:10) at exports.getProduct (/Users/huynhhuukhanh/HKhansh/BE/Learn-NodeJS/refactoring-MVC-pattern/controllers/products.js:20:11) at Layer.handle [as handle_request] (/Users/huynhhuukhanh/HKhansh/BE/Learn-NodeJS/node_modules/express/lib/router/layer.js:95:5) at next (/Users/huynhhuukhanh/HKhansh/BE/Learn-NodeJS/node_modules/express/lib/router/route.js:137:13) at Route.dispatch (/Users/huynhhuukhanh/HKhansh/BE/Learn-NodeJS/node_modules/express/lib/router/route.js:112:3) at Layer.handle [as handle_request] (/Users/huynhhuukhanh/HKhansh/BE/Learn-NodeJS/node_modules/express/lib/router/layer.js:95:5) at /Users/huynhhuukhanh/HKhansh/BE/Learn-NodeJS/node_modules/express/lib/router/index.js:281:22 at Function.process_params (/Users/huynhhuukhanh/HKhansh/BE/Learn-NodeJS/node_modules/express/lib/router/index.js:335:12) at next (/Users/huynhhuukhanh/HKhansh/BE/Learn-NodeJS/node_modules/express/lib/router/index.js:275:10) at Function.handle (/Users/huynhhuukhanh/HKhansh/BE/Learn-NodeJS/node_modules/express/lib/router/index.js:174:3)
模型/product.js 中的代码
odule.exports = class Product {
constructor(title) {
this.title = title;
}
save() {
this._getProductsFromFile((products) => {
products.push(this);
fs.writeFile(
path.join(
path.dirname(process.mainModule.filename),
"data",
"products.json"
),
JSON.stringify(products),
(err) => {}
);
});
}
static fetchAll(cb) {
this._getProductsFromFile(cb);
}
_getProductsFromFile(cb) {
fs.readFile(
path.join(
path.dirname(process.mainModule.filename),
"data",
"products.json"
),
(err, fileContent) => {
if (err) cb([]);
else cb(JSON.parse(fileContent));
}
);
}
};
控制器/products.js 中的代码
const Product = require("../models/product");
exports.postAddProduct = (req, res, next) => {
const product = new Product(req.body.title);
product.save();
res.redirect("/");
};
exports.getProduct = (req, res, next) => {
Product.fetchAll((products) => {
res.render("shop", {
prods: products,
pageTitle: "Shop",
path: "/",
hasProducts: products.length > 0,
activeShop: true,
productCSS: true,
});
});
};
我需要一些帮助,谢谢大家。
解决方案
推荐阅读
- vue.js - VuetifyJS - 滚动 v-navigation-drawer
- coldfusion - 如何隐藏cfgrid默认底部工具栏?
- php - 如何自动计算价格和数量然后显示结果?AJAX PHP
- javascript - 我无法将元素移动到最后位置和第一个位置
- sql - 根据另一列计算 + 和 - 值的数量
- node.js - 无法使用 Node.js 和 Crontab
- symfony - 表单字段标签显示两次
- rx-java - 我怎样才能确保 RXJava Observable 只发出并且恰好 1 项
- python-3.x - 如何识别两个数据帧之间的确切行匹配并打印其上方的行
- javascript - 将 JavaScript 对象传递给另一个函数