Will this .myObj = myObj store the link or copy / snapshot?

If myObj is a javascript object, there will be

this.myObj = myObj

create a copy / snapshot of what this object looks like at the moment, or will it keep a link to the actual object?

I'm having problems with what seems like a double set of the same object, so I start to wonder if I really support copies when I don't want to ...

+3
source share
3 answers

Link of course:

var foo = function () {};
var foo_instance = new foo();
var bar = {
    foo: foo_instance
};
console.log(foo_instance === bar.foo);    // true

If you want to clone an object, you have two alternatives:

JQuery

var foo = function () {};
var foo_instance = new foo();

var foo_instance_clone = new foo();
$.extend(foo_instance_clone, foo_instance);

Pure JavaScript:

var foo = function () {};
var foo_instance = new foo();

var foo_instance_clone = new foo();
for (var key in foo_instance) {
    if (foo_instance.hasOwnProperty(key)) {
        foo_instance_clone[key] = foo_instance;
    }
}
0
source

This is a reference to an object. There is one object with two “addressing” methods.

function Cls(obj) {
  this.myObj = obj;
}

var foo = { bar : 1 }
var x = new Cls(foo);

foo.bar = 2;
console.log(x.myObj) // { bar : 2 }
+2
source

You simply assign a link to an object. In the end, you only deal with links in ECMAscript. There is no such thing as an “actual object” with which you can deal in memory or clone it. Well, you can clone it, but it will just create another object in HEAP where you will get the link.

Think of it this way ...

var newObj = { };

Now it happens that a new object is formed / created somewhere on HEAP, and you have a link to this in your variable newObj. When we go like

newObj.foo = newObj

we are just referring to the same object somewhere on HEAP. No magic at all.

+2
source

All Articles