我有BookingOrder类它是主容器类,我在主容器中嵌套了像PickAddress这样的类。
如果我们发起一个类型为BookingOrder的对象,那么我们为PickupAddress.EnteredAddress Property分配一个值,然后我们再次尝试启动BookingOrder的另一个对象,我们会发现 此新对象中的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>
每次调用构造函数时,它将返回新的新对象,并且不使用原型再次启动所有嵌套对象,并在构造函数中再次清除所有值。
答案 0 :(得分:1)
当您引用“PickupAddress”对象时,您总是引用同一个对象。如果你需要为每个实例刷新它,你必须在构造函数中设置它。
function BookingOrder() {
this.PickupAddress = {
"EnteredAddress": null,
"EstablishmentName": null,
"GeoPoint": { "lat": 0, "lng": 0 }
};
}
现在每次调用构造函数都会确保每个实例都有自己的“PickupAddress”属性,该属性具有自己的不同值(对象)。