admin 管理员组

文章数量: 1086019

I have a function that should return two variables, thisYear and nextYear when I pass a date to the function. However, when I call .add on date it is changing the value of thisYear even though thisYear was already set.

Function and call

/

var someDate = moment()
thisYearAndNextYear(someDate)

function thisYearAndNextYear(date) {
  const thisYear = date
  console.log("thisYear = " + thisYear);
  const nextYear = date.add(1, 'year')
  console.log("nextYear = " + nextYear);
  console.log("thisYear (after nextYear set) = " + thisYear);
}

Output

thisYear = 1522021438255
nextYear = 1553557438255
thisYear (after nextYear set) = 1553557438255  // ISSUE: this should still be 1522021438255

Does anyone understand how to prevent this odd behavior such that thisYear retains its initial value?

I have a function that should return two variables, thisYear and nextYear when I pass a date to the function. However, when I call .add on date it is changing the value of thisYear even though thisYear was already set.

Function and call

http://jsfiddle/rLjQx/29945/

var someDate = moment()
thisYearAndNextYear(someDate)

function thisYearAndNextYear(date) {
  const thisYear = date
  console.log("thisYear = " + thisYear);
  const nextYear = date.add(1, 'year')
  console.log("nextYear = " + nextYear);
  console.log("thisYear (after nextYear set) = " + thisYear);
}

Output

thisYear = 1522021438255
nextYear = 1553557438255
thisYear (after nextYear set) = 1553557438255  // ISSUE: this should still be 1522021438255

Does anyone understand how to prevent this odd behavior such that thisYear retains its initial value?

Share Improve this question asked Mar 25, 2018 at 23:52 RbarRbar 3,9489 gold badges45 silver badges70 bronze badges 1
  • That is how moment works. It has cloning options, but if you want a library that never modifies your dates, you might check out date-fp. – Scott Sauyet Commented Mar 26, 2018 at 0:15
Add a ment  | 

1 Answer 1

Reset to default 13

Objects are passed by reference. When you pass an variable referencing an object to a function, that function still gets a reference to the original object. You can think of it like this: variables for non-primitives (such as objects) reference memory addresses, and those memory addresses get passed around.

So, when you call add on the moment object, the object gets mutated.

If you want to clone the moment object so you can operate on a copy of it:

https://momentjs./docs/#/parsing/moment-clone/

call the .clone() method.

const nextYear = date.clone();
nextYear.add(1, 'year')

本文标签: javascriptmoment()add changes previously set variableStack Overflow