[英]How do I create Objects in Javascript, so I can later access their properties?
I am filling an array with objects using this code: 我使用以下代码用对象填充数组:
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())}
When I try to access the objects in the array later on, I get an error message saying "Cannot read property 'orderDate' of undefined". 稍后尝试访问数组中的对象时,收到一条错误消息,提示“无法读取未定义的属性'orderDate'”。 Here is the code I use to access the objects:
这是我用来访问对象的代码:
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);
}
})
})
I am writing a small sample application to learn a little about nodejs. 我正在编写一个小的示例应用程序,以了解有关nodejs的一些知识。 All I want to do is create an order, and after 5 seconds, the order shall be ready (returning some message to the client who ordered)
我要做的就是创建一个订单,并在5秒钟后准备好订单(向订购的客户返回一些消息)
I uploaded my full code in case anyone wants to look at it (some of the strings are in german though): server.js mensa.js 我上载了完整的代码,以防万一有人想看(虽然有些字符串是德语的): server.js mensa.js
getOrder
is not being used as a constructor, so the this
reference actually points to a different object than what is being returned. getOrder
未被用作构造函数,因此, this
引用实际上指向的对象与返回的对象不同。 Change it to function Order()
and call it with orders.push( new Order() )
instead: 将其更改为
function Order()
,然后使用orders.push( new Order() )
调用:
function Order(orderName, sender) {
this.orderName = orderName;
this.orderDate = new Date();
this.sender = sender;
}
Usage: 用法:
dishEmitter.on('order', function(orderName, sender){
orders.push( new Order( orderName, sender ) );
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.