1

I use Node.js and I want to assign current value of A to variable B.Value of B should not change when changes happen to A.

var A = new Date();
var B = A;
DP.setMonth(A.getMonth() - 1);
console.log(B); //get A result
heshjse
  • 878
  • 2
  • 14
  • 30
  • You can't directly, objects are always assigned by reference, not value. You would have to clone the object. – Alexander O'Mara May 03 '16 at 05:20
  • replace `var B = A;` with `var B = new Date(A);` or simply `var B = new Date();` – gurvinder372 May 03 '16 at 05:20
  • this is only a example if I assign object value to another variable, that variable values always change with first object.how to create another object with the assigning object value. – heshjse May 03 '16 at 05:27

3 Answers3

2

I use Node.js and I want to assign current value of A to variable B.Value of B should not change when changes happen to A.

Simply replace

var B = A;

with

var B = new Date(A);

If you want to use value of A, but still want both of them to be isolated from each other than you need to make a new object rather than simply referring to old one.

gurvinder372
  • 66,980
  • 10
  • 72
  • 94
2

You can create a new Date object and seed it with A's value.

var A = new Date();
var B = new Date(A.getTime());

A.setMonth(A.getMonth() - 1);

console.log(B);
Nadh
  • 6,987
  • 2
  • 21
  • 21
1

The most efficient way to do this(clone objects in JS) is to use a third party utility library called Lodash.

Using lodash you can simply clone or deep clone(for nested objects) by using the following functions: _.clone() or _cloneDeep()

Install Lodash by npm install --save lodash

var _ = require(lodash)
var A = new Date();
var B = _.cloneDeep(A);
DP.setMonth(A.getMonth() - 1);
console.log(B);// B will not change

You can use these methods to clone most of JS objects. Lodash is highly optimized for performance so it would be better to use Lodash than manually cloning each keys. Lodash also offers other extremely usefull functions.

Nidhin David
  • 2,426
  • 3
  • 31
  • 45
  • loadsh is very heavy, finally adding a lot of package every one with lodash produce a big file, now i'm working hard to avoid lodash – stackdave Mar 28 '18 at 08:52