I Have BookingOrder Class it's the main container Class , I have nested classes like PickAddress in thie main container .
If we initiate an object of type BookingOrder then we assign PickupAddress.EnteredAddress Property a value then we try again to initiate another object of BookingOrder we will find PickupAddress.EnteredAddress in this new object has the old value , why it's not initiate again .
- Click on the button
- it will call fill order function and i will fill o.PickupAddress.EnteredAddress.
- Click on the button again .
- it will call fill order function and initiate new bookingorder() , but it will give you alert that o.PickupAddress.EnteredAddress has value .
I need to know why is this happening and what i should do to initiate all the objects in the main complex object .
<!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>
the best option for doing that like this:
<!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>
Each Time you invoke the constructor it will return fresh new object and all the nested objects initiated again without using prototype and clear all the values again in the constructor.