Reputation: 11830
I want to understand how we can declare a variable inside the class?
For example, Until now, I have been declaring it like this
let displaySearchCrypto = []
let updateCoinData = [];
class cryptoTicker extends PureComponent {
and using it throughout my class (I mean inside my class like this)
componentDidUpdate() {
updateCoinData = [...this.props.cryptoLoaded];
if (updateCoinData[i]["short"] == tradeMsg.coin ) {
//Search for changed Crypto Value
updateCoinData[i]["long"] = tradeMsg["message"]["msg"]["long"]
updateCoinData["short"] = tradeMsg["message"]["msg"]["short"]
or
search = () => {
displaySearchCrypto.push({
no: {i},
key: this.props.cryptoLoaded[i]["long"],
short: this.props.cryptoLoaded[i]["short"],
long: this.props.cryptoLoaded[i]["long"],
price: this.props.cryptoLoaded[i]["price"],
mktcap: this.props.cryptoLoaded[i]["mktcap"],
perc: this.props.cryptoLoaded[i]["perc"],
vwapData: this.props.cryptoLoaded[i]["vwapData"]
})
But, Since I am going to use inside a single class only, I think I shouldn't declare in global scope class. So my question is, How to declare a variable inside the class?
Upvotes: 1
Views: 823
Reputation: 36580
Yes I think T.J Crowder anwsers this very nicely. However I would like to add the following:
The task of Objects and classes is to provide abstractions of certain entities. In the case of ReactJS these objects are react components. The advantage of putting all the data related to a certain component inside an object provides the following advantages:
Also remember:
Classes have:
Furthermore it is important to know that JS uses prototypal inheritance. The class
keyword is merely syntactic sugar build on top prototypal inheritance.
Upvotes: 0
Reputation: 1074038
You don't declare variables inside a class. You declare variables within a constructor or method, or you create properties of an instance (or the class itself, "static" properties, which are properites on the constructor function).
If you're using modules, your first code block won't create globals, it will create module-globals (global only to code in that module). If that module contains only that class, and you mean for the variables and the arrays they refer to to be shared by all instances of that class, you can keep doing it that way.
But I suspect you want them to be properties of the instance, not shared between instances, in which case you define those properties in the constructor:
constructor(props) {
super(props);
this.displaySearchCrypto = [];
this.updateCoinData = [...this.props.cryptoLoaded];
}
Then use them by referring to the instance (usually via this.
).
Upvotes: 3