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

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

问题描述

(这个问题不是特定于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,
  );

我不希望变量为 primaryNumber typeOfExpression 了,我希望它们是 this.primaryNumber 这个。 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;

但这不是最佳方式!我该怎么办?如果我在 {} 中的变量前面添加这个,我会收到一个错误,如果我删除了它不接受 = 谢谢。

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天全站免登陆