JavaScript: save object as fixed value?

I noticed this behavior when writing my JavaScript, and I could not understand why:

Below is the code to reproduce the behavior in question.

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

Expected Result: Browser Warning 1, because I only changed the property of the o2 object , not the o1 object .

Actual result: The browser warns 2, because it seems that o1 is equal to o2 .

I'm not sure what is going on. How can I fix the code so that it warns 1 and 2 (assuming that o1 has not changed)?

Thank you very much in advance.

+3
3

. / . .

JavaScript , () OO .

+5

var o2 = o1;, o1 o2 . , , o1 o2. JavaScript.

+3

Because you are setting objects at the same control point. You need to clone an object. here is a code snippet http://www.thespanner.co.uk/2008/04/10/javascript-cloning-objects/ , which allows you to clone objects with a prototype.

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

All Articles