如何在对象解构赋值的左侧使用它? [英] How can I use this in the left side of the object destructuring assignment?

查看:18
本文介绍了如何在对象解构赋值的左侧使用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(这个问题不是Vue特有的,而是在一个Vue项目中,这就是为什么在函数和变量前面奇怪地使用了this.)

(This question is not specific to Vue, but it is in a Vue project, that is why the strange use of the this in front of the functions and variables.)

我有一个函数返回一个被分解为两个变量的对象:

I have a function that returns an object which is destructured into two variables:

  const { primaryNumber, typeOfExpression } = this.findPrimaryAndType(
    this.naturalExpressionYearOfBirth,
    this.gender,
  );

我不希望变量是 primaryNumbertypeOfExpression,我希望它们是 this.primaryNumberthis.typeOfExpression 指的是我的视图数据部分.

I don't want the variables to be primaryNumber and typeOfExpression any more, I want them to be this.primaryNumber and this.typeOfExpression which refer to my view data section.

我使用下面的代码找到了一个糟糕的解决方法:

I have found a crummy workaround using the code below:

  this.primaryNumber = primaryNumber;
  this.typeOfExpression = typeOfExpression;

但这不可能是最好的方法!我该怎么办?如果我在 {} 内的变量前面添加 this 我会得到一个错误,如果我删除 const 它不接受 =谢谢.

But this can't be the best way of doing it! What should I do? If I add this in front of the variables inside the {} I get an error and if I remove the const it does not accept the = Thanks.

推荐答案

您可以拼出解构目标,而不是隐式地创建 const 变量:

You can spell out the destructuring targets, instead of implicitly creating const variables:

({
  primaryNumber: this.primaryNumber,
  typeOfExpression: this.typeOfExpression
} = this.findPrimaryAndType(
  this.naturalExpressionYearOfBirth,
  this.gender,
));

当然,这在简洁方面不是很有帮助.如果这两个属性是结果对象上的唯一属性,则您可以使用 Object.assign:

Of course that's not very helpful in terms of conciseness. If those two properties are the only ones on the result object, you can however use Object.assign:

Object.assign(this, this.findPrimaryAndType(
  this.naturalExpressionYearOfBirth,
  this.gender,
));

这篇关于如何在对象解构赋值的左侧使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆