Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
465 views
in Technique[技术] by (71.8m points)

javascript - How can I use this in the left side of the object destructuring assignment?

(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,
  );

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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,
));

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,
));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...