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