首页  >  问答  >  正文

如何在函数调用之前改变一个对象?这真的可行吗?

<p>我有一个非常奇怪的js问题。我有一个Vue组件(但我认为Vue在这里不重要)。它有一个名为<code>current_query</code>的数据属性。在响应事件的方法中,我想修改该属性。在这里使用Lodash。有一个非常奇怪的行为。假设<code>this.current_query</code>最初等于<code>{ test: 500 }</code>。假设<code>'field'</code>参数为<code>'test'</code>。通过从<code>current_query</code>中“取消设置”它,实际上我将清空current_query本身。很好。问题是,只有在使用unset时,如果我在调用unset之前记录current_query,我将得到一个空对象。这怎么可能?</p> <pre class="brush:php;toolbar:false;">on_applied_option_click(field){ console.log(this.current_query); // 给出{ test: 500 }(OK) }, // 点击结束 on_applied_option_click(field){ console.log(this.current_query); // 只有在使用_.unset时,才会给出空对象(??) _.unset(this.current_query, field); console.log(this.current_query); // 也会给出空对象(OK) }, // 点击结束</pre> <p>我发现如果我使用<code>_.omit</code>,一切都很好:</p> <pre class="brush:php;toolbar:false;">on_applied_option_click(field){ console.log(this.current_query); // 给出{ test: 500 }(OK) this.current_query = _.omit(this.current_query, field); console.log(this.current_query); // 给出空对象,此时是可以的 }, // 点击结束</pre> <p>为什么?我唯一能说的是,_.unset会改变对象,而_.omit会创建新对象。但是,我认为在调用之前,_.unset改变对象是不可能的(???)。从未见过这样的事情。有人对这种奇怪的行为有什么好的解释吗?</p>
P粉539055526P粉539055526415 天前392

全部回复(1)我来回复

  • P粉301523298

    P粉3015232982023-08-31 10:43:44

    不要使用console.log(this.current_query),尝试使用console.log(JSON.stringify(this.current_query))。这样可以可靠地记录this.current_query在记录时的状态,而不是可能之后的某个状态。

    这样应该可以解决混淆问题。

    回复
    0
  • 取消回复