0

I have an object that has a method. Inside that method is a function, I want to use my object property inside the function of my method.

this is what I'm doing right now:

const obj ={ property: 5, method(){ //deconstructing this obj const {property} = this; // a function inside a method const func1 = () =>{ console.log(property + 5); } } } 

I destructured the obj inside its method because I don't want to keep on doing this.property or obj.property when I'm using my obj property inside the function of my method. Is this bad and is there a better way to do this?

1 Answer 1

2

It's just fine to grab a local copy of the value of a property like that. Just note that it is a copy of the value,¹ so if something in the method or a method it calls changes the property value, you won't see that change in your local copy. For example:

const obj = { property: "original", method() { const {property} = this; console.log(`property = ${property}, this.property = ${this.property}`); this.changeProperty() console.log(`property = ${property}, this.property = ${this.property}`); }, changeProperty() { this.property = "UPDATED"; } }; obj.method();

Sometimes that's why you're doing it, to make sure you see the same value throughout. But there's nothing wrong with doing it for convenience if you like.

Another thing to beware of is doing this with methods, because there's an important difference between this.method(); and const {method} = this; method();: The former ensures this is set correctly, the latter doesn't.


¹ It isn't in your example, but if the "value" is an object reference note that it's just a copy of the reference; the object isn't copied.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the quick feedback! I didn't know that it was actually just copying the value of the property.
@JohnHinrichJosephG.Galindo - My pleasure! Yes, it's a copy, but usually that's absolutely fine. FWIW, you see this a lot in the render method of class components in React, things like: const {a, b, c} = this.state; and then using a, b, and c in the returned elements. Happy coding!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.