开发者

JavaScript: Store Object as Fixed Value?

开发者 https://www.devze.com 2023-02-16 06:16 出处:网络
I\'ve noticed this behavior when writing my JavaScript, and I haven\'t been able to figure out why:开发者_运维知识库

I've noticed this behavior when writing my JavaScript, and I haven't been able to figure out why:

开发者_运维知识库

Below is some code to reproduce the behavior in question.

var o1 = {
  num: 1
}
var o2 = o1;
o2.num = 2;
alert(o1.num);

Expected Result: The browser alerts 1, because I only changed a property of the o2 object, not the o1 object.

Actual Result: The browser alerts 2, because it seems o1 is equal to o2.

I'm not really sure what's going on. How can I fix the code so it alerts 1 rather that 2 (assuming that o1 hasn't changed)?

Much thanks in advance.


Because both variables reference the same object. Objects are not cloned/copied on variable assignment. You would have to do this yourself.

JavaScript behaves the same way like any (most) other OO languages in this case.


By writing var o2 = o1; you're making o1 and o2 two references to the same object. What you want to do is to clone the o1 object and to store the cloned copy in o2. Search for cloning objects in JavaScript.


Because you are setting the objects to the same reference point. You need to clone the object. here is a piece of code from http://www.thespanner.co.uk/2008/04/10/javascript-cloning-objects/ that allows for cloning of objects with prototyping.

Object.prototype.clone = function() {
  return eval(uneval(this));
}
alert("test".clone());
alert((3).clone());
alert(clone.clone());
0

精彩评论

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