代码之家  ›  专栏  ›  技术社区  ›  Rbar

力矩()。添加以前设置的变量的更改

  •  1
  • Rbar  · 技术社区  · 8 年前

    我有一个函数,它应该返回两个变量, thisYear nextYear 当我向函数传递日期时。然而,当我打电话时 .add 在…上 date 它正在更改 今年 尽管 今年 已设置。

    函数和调用

    http://jsfiddle.net/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);
    }
    

    输出

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

    有人知道如何防止这种奇怪的行为吗 今年 是否保留其初始值?

    1 回复  |  直到 8 年前
        1
  •  6
  •   CertainPerformance    8 年前

    对象通过引用传递。将引用对象的变量传递给函数时,该函数仍会获得对原始对象的引用。您可以这样想:非基本体(如对象)的变量引用 内存地址 ,这些内存地址就会被传递。

    所以,当你打电话的时候 add 在矩对象上,对象发生变化。

    如果要克隆力矩对象以便可以对其副本进行操作,请执行以下操作:

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

    致电 .clone() 方法

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