I'm working on a Point object
function Point(x, y) {
this.x = x;
this.y = y;
};
The current implementation allows the Point object to be mutable. For example:
var p = new Point(2, 3);
p.x = 6;
However, I want to add a clone method to create a new instance with the same properties:
var p1 = new Point(2, 3);
var p2 = p1.clone();
p1.x = 6;
assert p1 != p2; // Checking if p1 and p2 are different objects
assert p2.x == 2; // Verifying that the x property of p2 remains unchanged
To implement the clone()
method, I modified the Point constructor as follows:
function Point(x, y) {
this.x = x;
this.y = y;
this.clone = function () {
function TrickyConstructor() {
}
TrickyConstructor.prototype = this;
return new TrickyConstructor();
};
};
Despite these changes, the second assertion is failing in my implementation. How should I proceed to reimplement it?