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 
3
  • You can't directly, objects are always assigned by reference, not value. You would have to clone the object. Commented May 3, 2016 at 5:20
  • replace var B = A; with var B = new Date(A); or simply var B = new Date(); Commented May 3, 2016 at 5: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. Commented May 3, 2016 at 5:27

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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); 

Comments

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.

1 Comment

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.