关于javascript中克隆的简单问题
我有一个观点
function Point(x, y) {
this.x = x;
this.y = y;
};
,正如你所看到的,它是可变的。所以我可以更改它的属性,就像
var p = new Point(2, 3);
p.x = 6;
我想添加克隆方法一样,以便预期的行为是
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.
为了实现clone(),我用下一种方式重写Point
function Point(x, y) {
this.x = x;
this.y = y;
this.clone = function () {
function TrickyConstructor() {
}
TrickyConstructor.prototype = this;
return new TrickyConstructor();
};
};
但是第二个断言对于我的实现失败了。我应该如何重新实现它?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果属性只有
x
和y
,我会这样做:请注意,我将
clone
方法附加到Point.prototype< /代码>。这对于下一个方法的工作非常重要:
如果没有,您将必须创建一个新实例,并且可能将所有属性复制到新实例:
但这将不会深度复制属性。这仅适用于原始值。
如果您确实想要深层复制属性,这可能会变得更加复杂。 ,之前已经有人问过这个问题:如何在 javascript 中进行深度克隆
幸运的是 为什么你的克隆方法不起作用:
p2
的原型链将如下所示:所以如果你设置
p1.x = 6
它将是:只要
p2
没有自己的x
或y
属性,它们将始终引用恰好发生的原型的属性是p1
。If the properties are only
x
andy
, I would do this:Note that I attach the
clone
method 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
p2
will look like this:so if you set
p1.x = 6
it will be:As long as
p2
has no ownx
ory
properties, they will always refer to the ones of the prototype which happens to bep1
.示例: http://jsfiddle.net/HPtmk/
Example: http://jsfiddle.net/HPtmk/