开发者

Simple question about clone in javascript

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 p开发者_如何学编程2.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 x and y, I would do this:

function Point(x, y) {
    this.x = x;
    this.y = y;
};

Point.prototype.clone = function() {
    return new Point(this.x, this.y);
}

Note that I attach the clone method to Point.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:

Point.prototype.clone = function() {
    var clone = new Point(this.x, this.y);
    for(var prop in this) {
        if(this.hasOwnProperty(prop)) {
            clone[prop] = this[prop];
        }
    }
    return clone;
}

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 p2 will look like this:

 +-----------+      +-----------+
 |Instance p2|      |Instance p1|
 |           |----->|x=2        |
 |           |      |y=3        |
 +-----------+      +-----------+

so if you set p1.x = 6 it will be:

 +-----------+      +-----------+
 |Instance p2|      |Instance p1|
 |           |----->|x=6        |
 |           |      |y=3        |
 +-----------+      +-----------+

As long as p2 has no own x or y properties, they will always refer to the ones of the prototype which happens to be p1.


function Point(x, y) {
    this.x = x;
    this.y = y;
    this.clone = function () {
        var newPoint = {};
        for (var key in this) {
            newPoint[key] = this[key];
        }
        return newPoint;
    };
};

Example: http://jsfiddle.net/HPtmk/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜