Javascript 无法读取es6类变量(无法读取未定义的
所以我第一次跳入es6,想使用新的类,但我遇到了一个奇怪的问题。所有类都可以正常工作,并且可以很好地写入/读取它们的类变量。但有一个班级表现不太好 我当前遇到以下错误:Javascript 无法读取es6类变量(无法读取未定义的,javascript,express,ecmascript-6,Javascript,Express,Ecmascript 6,所以我第一次跳入es6,想使用新的类,但我遇到了一个奇怪的问题。所有类都可以正常工作,并且可以很好地写入/读取它们的类变量。但有一个班级表现不太好 我当前遇到以下错误: TypeError:无法读取未定义的属性“product” 在getProducts(***/controllers/ProductController.js:41:13) 我正在使用均值堆栈为学校作业编写RESTAPI 简言之,目前正在发生什么 index.js /路由/api.js routes/api/products.j
TypeError:无法读取未定义的属性“product”
在getProducts(***/controllers/ProductController.js:41:13)
我正在使用均值堆栈为学校作业编写RESTAPI
简言之,目前正在发生什么
index.js
/路由/api.js
routes/api/products.js
models/Product.js
控制器/ProductController.js
错误发生在this.product.find()处
当我console.log(this.product)
设置它之后,它立即返回正常。但是当我用GET athttp://localhost:port/api/products
我收到了这个错误
此外,当我尝试在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中,您只需传入方法,这意味着调用这些方法时,它们不会设置。您需要绑定它们,例如:
.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的方法也执行此操作。不过,您需要将其绑定到this.controller
。也许箭头函数是一个更简单的解决方案。@Bergi,谢谢,关于接收器的好消息。还添加了箭头示例。如果您不知道参数的数量或参数太多,无法将其拼出来,也可以使用rest/spread语法:(…args)=>this.controller.getProducts(…args)
// 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)
// 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
}
}
class ProductController
{
constructor()
{
this.product = require('../models/product')
}
init()
{
console.log('hi!')
}
getProducts(req, res, next)
{
this.init()
... // rest of code
}
}
.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)])