简体   繁体   中英

Why to declare variable in the class, even assigning that variable to this in the constructor

In the code below, as you can see I declared a variable constObj in the Test class. And at the same time assigning constObj object to this in the constructor.

Why do we need to declare the variable again, even though we already assigning it to this in the constructor?

In the webstorm IDE, it is throwing error doesn't have the property constObj , if I do this.constObj , if the variable is not declared. But the code is working fine without issues.

Is declaring the variable mandatory, even if we are assigning that to this

 const constObj = { a: function() { console.log("sivakumar"); } }; class Test { constObj: any; // Is this line mandatory? I mean declaring it??? constructor() { Object.assign(this, { constObj }); } callMethod() { this.constObj.a(); } } new Test().callMethod(); 

Please let know, what will happen, if we don't declare.

Is declaring the variable is mandatory...

It's not a variable, it's a property.

The answer for TypeScript : Yes, it's mandatory, so that TypeScript knows that Test has that property for the purposes of doing its static type checks. (Note that the way you've done it is just one of the possible ways of declaring that property. But you do need to declare it.)

The answer for JavaScript : No, it's not mandatory¹, because JavaScript doesn't do static type checks.


¹ (and it's not possible per the current specification, but it soon will be and is commonly transpiled with tools like Babel )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM