我有BookingOrder类,它是主容器类,我在主容器中嵌套了像PickAddress这样的类。Javascript中的复杂对象
如果我们启动类型BookingOrder的对象,然后我们分配PickupAddress.EnteredAddress属性的值,然后我们再尝试启动BookingOrder的另一个目的,我们将在这个新的对象找到 PickupAddress.EnteredAddress有旧值,它为什么不再次启动。
- 单击按钮
- 它会调用填写以下功能,我将填补o.PickupAddress.EnteredAddress。
- 再次点击按钮。
- 它会调用填充顺序函数并启动新的订单顺序(),但它会提醒您o.PickupAddress.EnteredAddress具有值。
我需要知道为什么会发生这种情况以及我应该如何启动主复杂对象中的所有对象。
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script>
function BookingOrder() { }
BookingOrder.prototype = {
"DriverLng": null,
"AccountName": null,
"ParaTransit": false,
"PickupAddress": {
"EnteredAddress": null,
"EstablishmentName": null,
"GeoPoint": { "lat": 0, "lng": 0 }
},
"DropoffAddress": {
"EnteredAddress": null,
"EstablishmentName": null,
"GeoPoint": { "lat": 0, "lng": 0 }
}
};
var o;
function FillOrder() {
debugger;
o = new BookingOrder();
if (o.PickupAddress.EnteredAddress != null & o.PickupAddress.EnteredAddress != '')
alert('Entered Address is not empty');
else
o.PickupAddress.EnteredAddress = 'Test 123'
}
</script>
</head>
<body>
<input type="button" onclick="FillOrder()" />
</body>
</html>
这样做,像这样是最好的选择:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script>
function BookingOrder() {
return {
"DriverLng": null,
"AccountName": null,
"ParaTransit": false,
"PickupAddress": {
"EnteredAddress": null,
"EstablishmentName": null,
"GeoPoint": { "lat": 0, "lng": 0 }
},
"DropoffAddress": {
"EnteredAddress": null,
"EstablishmentName": null,
"GeoPoint": { "lat": 0, "lng": 0 }
}
};
}
var o;
function FillOrder() {
debugger;
o = new BookingOrder();
if (o.PickupAddress.EnteredAddress != null & o.PickupAddress.EnteredAddress != '')
alert('Entered Address is not empty');
else
o.PickupAddress.EnteredAddress = 'Test 123'
}
</script>
</head>
<body>
<input type="button" onclick="FillOrder()" />
</body>
</html>
在每次调用构造函数将返回全新的对象和所有再次发起嵌套的对象,而无需使用原型,并清除所有的值再次在构造函数中。
........... what –
怎么能有人明白你在说什么?更清楚您的问题和代码。 –
[Crockford的Prototypal继承 - 嵌套对象的问题]的确切副本[JavaScript原型继承 - 共享属性](http://stackoverflow.com/questions/10131052/crockfords-prototypal-inheritance-issues-with-nested-objects) (http://stackoverflow.com/questions/15449838/javascript-prototype-inheritance-shared-property) – Bergi