[英]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. 在下面的代码中,正如您所看到的,我在
Test
类中声明了一个变量constObj
。 And at the same time assigning constObj
object to this
in the constructor. 同时在构造函数中
this
指定constObj
对象。
Why do we need to declare the variable again, even though we already assigning it to this
in the constructor? 为什么我们需要再次声明的变量,即使我们已经将其分配给
this
构造函数?
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. 在
webstorm
IDE中,抛出错误doesn't have the property constObj
,如果我执行this.constObj
,如果未声明变量。 But the code is working fine without issues. 但代码工作正常没有问题。
Is declaring the variable mandatory, even if we are assigning that to this
声明变量是强制性的,即使我们将其赋值给
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. TypeScript的答案 :是的,它是必需的,因此TypeScript知道
Test
具有该属性以进行静态类型检查。 (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. JavaScript的答案 :不,它不是必需的¹,因为JavaScript不进行静态类型检查。
¹ (and it's not possible per the current specification, but it soon will be and is commonly transpiled with tools like Babel ) ¹(根据当前的规范,这是不可能的,但它很快就会出现并且通常用像Babel这样的工具进行转换)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.