【问题标题】:A function is mutating an object before being called: how is it possible? [duplicate]一个函数在被调用之前正在改变一个对象:这怎么可能? [复制]
【发布时间】:2021-11-28 06:27:25
【问题描述】:

我有一个很奇怪的 js 问题。我有一个 Vue 组件(但我认为 Vue 在这里并不重要)。它有一个名为current_query 的数据属性。在响应事件的方法上,我想修改该属性。在这里使用 Lodash。还有一个非常奇怪的行为。假设 this.current_query 最初是 == { test: 500 }。还说'field' 参数是'test'。通过从current_query '取消设置'它,实际上我将清空 current_query 本身。完美的。事情是,(仅)在使用 unset 时,如果我在调用 unset 之前记录 current_query 之前,我将得到一个空对象。怎么可能?

  on_applied_option_click(field){
    console.log(this.current_query); // gives { test: 500 } (OK)
  }, // end click

  on_applied_option_click(field){
    console.log(this.current_query); // gives empty object only if, and when, using _.unset  (??)
    _.unset(this.current_query, field);
    console.log(this.current_query); // gives empty object as well  (OK)
  }, // end click

我发现如果我改用_.omit,一切都会好起来的:

  on_applied_option_click(field){
    console.log(this.current_query); // gives { test: 500 }  (OK)
    this.current_query = _.omit(this.current_query, field);
    console.log(this.current_query); // gives empty object, which at this point is fine
  }, // end click

为什么?我唯一能说的是 _.unset 会改变对象,而 _.omit 会创建新的对象。但是,我仍然认为 _.unset 在被调用之前就改变对象是完全不可能的(???)。从来没有见过这样的事情。有人对这种奇怪的行为有什么好的解释吗?

【问题讨论】:

标签: javascript vue.js object lodash


【解决方案1】:

试试console.log(JSON.stringify(this.current_query)),而不是console.log(this.current_query)。这会可靠地记录 this.currenty_query 在记录时的状态,而不是之后的某些状态。

这应该可以解决混乱。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-30
    • 2019-08-03
    • 2019-01-09
    • 1970-01-01
    • 1970-01-01
    • 2012-06-09
    • 2021-07-16
    • 1970-01-01
    相关资源
    最近更新 更多