javascript - es6类变量无法读取(无法读取未定义的属性 '...')

标签 javascript express ecmascript-6

所以我第一次涉足 es6 并想使用新的类,但我遇到了一个奇怪的问题。所有类都工作正常并且可以很好地写入/读取它们的类变量。但有一个类(class)表现得不太好。

我目前收到此错误:

类型错误:无法读取未定义的属性“产品” 在 getProducts (***/controllers/ProductController.js:41:13)

我正在使用 MEAN Stack 为学校作业编写 REST API。

简而言之,目前正在发生什么

index.js

// dependencies
const Api  = require('./routes/api')

class Rest
{
    constructor()
    {
        this.api = new Api()
        this.init()
    }

    init()
    {
        ... // express server configuration

        // routes
        this.routes()
    }

    // set routes
    routes()
    {
        app.use('/api', this.api.getRouter())
    }
}

new Rest()

/routes/api.js

// dependencies
const express = require('express')
const Products = require('./api/products')

class Api
{
    constructor()
    {
        this.router = express.Router()
        this.products = new Products()
        this.routes()
    }

    getRouter() { return this.router }

    routes()
    {
        // product routes
        this.router.use('/products', this.products.getRouter())
    }
}


// return routes
module.exports = Api

routes/api/products.js

// dependencies
const express = require('express')
const productController = require('../../controllers/ProductController')

class Product
{
    constructor()
    {
        this.router = express.Router()
        this.controller = new productController()
        this.routes()
    }

    getRouter() { return this.router }

    // set header options
    setCollectionOptions(req, res, next)
    {
        res.header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')
        next()
    }

    // set routes
    routes()
    {
        this.router.route('/')
            .options([this.setCollectionOptions, this.controller.getOptions])
            .get([this.setCollectionOptions, this.controller.getProducts])
    }
}

// return routes
module.exports = Product

models/Product.js

// dependencies
const mongoose = require('mongoose')
const mongoosePaginate = require('mongoose-paginate')

// create schema for model
const productSchema = new mongoose.Schema({
    name: String,
    sku: String,
    price: String,
    created_at: { type: String, default: Date.now },
    updated_at: { type: String, default: Date.now }
})
productSchema.plugin(mongoosePaginate)

// export model
module.exports = mongoose.model('Products', productSchema)

controllers/ProductController.js

// dependencies
const express = require('express')

class ProductController
{
    constructor()
    {
        this.product = require('../models/product')
    }


    getProducts(req, res, next)
    {
        this.product.find() // error occurs here!
        ... // rest of the code
    }
}

错误发生在this.product.find()

当我console.log(this.product)时,在我设置它之后,它立即返回得很好。但是,当我在 http://localhost:port/api/products 处使用 GET 请求页面时,我收到此错误。

此外,当我尝试使用 ProductController 中的方法时,它会导致相同的错误。例如:

class ProductController
{
    constructor()
    {
        this.product = require('../models/product')
    }

    init()
    {
        console.log('hi!')
    }

    getProducts(req, res, next)
    {
        this.init()

        ... // rest of code
    }
}

提前致谢。

最佳答案

在routes/api/products.js中,您只是传递方法,这意味着当它们被调用时,它们不会设置this。您需要绑定(bind)它们,例如:

.get([this.setCollectionOptions.bind(this), this.controller.getProducts.bind(this.controller)])

或使用箭头函数,但这需要注意参数的数量:

.get([(req, res, next) => this.setCollectionOptions(req, res, next), (req, res, next) => this.controller.getProducts(req, res, next)])

不要忘记对传递给 .options 的方法也执行此操作。

关于javascript - es6类变量无法读取(无法读取未定义的属性 '...'),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40739943/

相关文章:

javascript - 吊装有什么好处吗?

javascript - 这段代码在 ES6 中的转置是什么?

javascript - 如何编写按钮 firefox 附加组件

php - 实时了解用户在我的站点中

javascript - 如何使用 Javascript 将多行数据放入图表中

javascript - Express.js 服务器端渲染 - 请求 '/json/version/

node.js - MongoError : driver is incompatible with this server version

javascript - 使用pm2时如何自动重新加载Node.js项目

javascript - RxJS 不能与 Math.random() 配合使用

JavaScript 原型(prototype)