[英]Why function becoming undefined?
我有快速會議,它在route方法中初始化:
router.post('/add', function (req, res) {
if (!req.session.cart) {
req.session.cart = cartController.initializeCart();
}
cartController.addToCart(req.body.productId, req.session.cart, function(error, result) {
error ? res.send(error) : res.send(200);
})
});
我有購物車模型作為功能
function cart() {
this.ids = [];
this.addProduct = function (id) {
ids.push(id);
}
}
初始化方法:
var cartModel = require("../models/cart"); //UPD
initializeCart: function() {
return new cartModel(); //UPD exception throw right after this operation
},
添加購物車方法:
addToCart: function(id, cart, callback) {
cart.addProduct(id);
.....
會議:
var expressSession = require('express-session');
app.use(expressSession({
secret: "someSecret"
}));
但是不會調用cart.addProduct(),因為addProduct()是未定義的。 使用原型對我沒有幫助。
屏幕: http : //prntscr.com/5rz61t
您的代碼中沒有cartModel
函數。
嘗試return new cart();
而不是return new cartModel();
如果cart
保存在不保留或恢復類型的會話存儲系統中,那么cart
將不再是購物車實例,而僅僅是一個簡單的對象。
router.post('/add', function (req, res) {
var cart;
cart = cartController.initializeCart();
if (req.session.cart) {
cart.ids = req.session.cart.ids;
} else {
req.session.cart = cart;
}
cartController.addToCart(req.body.productId, cart, function(error, result) {
error ? res.send(error) : res.send(200);
})
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.