首页 > 解决方案 > 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,
    });
  });
};

我需要一些帮助,谢谢大家。

标签: javascriptnode.jsclass

解决方案


推荐阅读