I have a Point
function Point(x, y) {
this.x = x;
this.y = y;
};
As you see, it’s mutable. So I can change it properties, like
var p = new Point(2, 3);
p.x = 6;
I want to add clone method so that expected behavior would be
var p1 = new Point(2, 3);
var p2 = p1.clone();
p1.x = 6;
assert p1 != p2; //first assertion. pseudocode.
assert p2.x == 2; //second assertion. pseudocode.
For implementing clone() I rewrite Point in next way
function Point(x, y) {
this.x = x;
this.y = y;
this.clone = function () {
function TrickyConstructor() {
}
TrickyConstructor.prototype = this;
return new TrickyConstructor();
};
};
But second assertion fails for my implementation. How should I reimplement it?
If the properties are only
xandy, I would do this:Note that I attach the
clonemethod toPoint.prototype. This is important for the next method to work:If not, you would have to create a new instance and maybe copy all properties to the new instance:
but this will not deep copy properties. This only works for primitive values.
If you really want to deep copy properties, this can get much more complex. Luckily, this has already been asked before: How to Deep clone in javascript
Explanation of why your clone method does not work:
The prototype chain of
p2will look like this:so if you set
p1.x = 6it will be:As long as
p2has no ownxoryproperties, they will always refer to the ones of the prototype which happens to bep1.