0% found this document useful (0 votes)
4 views

creational.prototype.explicit_copying.js

The document defines two classes, Address and Person, with methods for deep copying and string representation. A Person object, John, is created with an Address, and a deep copy of John is made as Jane. However, modifying Jane's address also affects John's, indicating a flaw in the deep copy implementation that requires recursive handling of nested objects.

Uploaded by

qsp41768
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

creational.prototype.explicit_copying.js

The document defines two classes, Address and Person, with methods for deep copying and string representation. A Person object, John, is created with an Address, and a deep copy of John is made as Jane. However, modifying Jane's address also affects John's, indicating a flaw in the deep copy implementation that requires recursive handling of nested objects.

Uploaded by

qsp41768
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

class Address

{
constructor(streetAddress, city, country) {
this.streetAddress = streetAddress;
this.city = city;
this.country = country;
}

deepCopy()
{
return new Address(
this.streetAddress,
this.city,
this.country
);
}

toString()
{
return `Address: ${this.streetAddress}, ` +
`${this.city}, ${this.country}`;
}
}

class Person
{
constructor(name, address)
{
this.name = name;
this.address = address; //!
}

deepCopy()
{
return new Person(
this.name,
this.address.deepCopy() // needs to be recursive
);
}

toString()
{
return `${this.name} lives at ${this.address}`;
}
}

let john = new Person('John',


new Address('123 London Road', 'London', 'UK'));

let jane = john.deepCopy();

jane.name = 'Jane';
jane.address.streetAddress = '321 Angel St'; // oops

console.log(john.toString()); // oops, john is called 'jane'


console.log(jane.toString());

You might also like