我使用以下代码填充数组:
orders.push(getOrder(orderName, sender));
...
function getOrder (orderName, sender){
this.orderName = orderName;
this.orderDate = new Date();
this.sender = sender;
console.log('Created order object.\n orderName: '+ orderName + '\n orderDate: ' + this.orderDate.getTime())}
当我稍后尝试访问数组中的对象时,我收到一条错误消息,提示"无法读取属性' orderDate'未定义"。这是我用来访问对象的代码:
dishEmitter.on('checkIfReady', function(){
orders.forEach(function(order){
console.log(order);
var now = new Date();
if(Math.abs((now.getTime() - order.orderDate.getTime()) / 1000) >= 5){
broadcast('Your ' + order.orderName + ' is ready!', order.sender);
orders.splice(indexOf(order),1);
}
})
})
我正在编写一个小型示例应用程序来了解nodejs。我想做的就是创建一个订单,5秒后,订单就准备好了(将一些消息返回给订购的客户)
答案 0 :(得分:3)
getOrder
未被用作构造函数,因此this
引用实际上指向的是与返回的对象不同的对象。将其更改为function Order()
,然后使用orders.push( new Order() )
进行调用:
function Order(orderName, sender) {
this.orderName = orderName;
this.orderDate = new Date();
this.sender = sender;
}
用法:
dishEmitter.on('order', function(orderName, sender){
orders.push( new Order( orderName, sender ) );
})