[英]Difference between initializing TypeScript variables in the class itself and doing it in the constructor
class cls {
str= 'hello';
}
vs 与
class cls {
str: string;
constructor() {
this.str = 'hello';
}
}
What is the difference between these two forms? 这两种形式有什么区别?
There is none. 空无一人。 This:
这个:
class Foo {
str = 'hello';
}
class Bar {
str: string;
constructor() {
this.str = 'hello';
}
}
will result in the following output: 将产生以下输出:
var Foo = (function () {
function Foo() {
this.str = 'hello';
}
return Foo;
}());
var Bar = (function () {
function Bar() {
this.str = 'hello';
}
return Bar;
}());
There is no specific difference here.But if you write below: 这里没有具体区别,但是如果您在下面写:
class cls {
str: string;
constructor(string str) {
this.str = str;
}
then on the time initialise of class you can assign the value to property. 然后在类的时间初始化时,您可以将值分配给属性。 For example :
例如 :
var obj1= new cls("obj1");
var obj2= new cls("obj2");
This won't possible with your first case. 您的第一种情况是不可能的。
When you choose to initialize variables in constructor it gives you an additional benefit of initializing those values at the time of object creation like this : 当选择在构造函数中初始化变量时,它为您提供了在创建对象时初始化这些值的其他好处,如下所示:
var obj1= new cls("obj1"); //Ability to change variable value
var obj2= new cls("obj2");
But when you do not initialize value in constructor, then you have to first create the object and then need to access that variable to change its value like this: 但是,当您不初始化构造函数中的值时,则必须首先创建对象,然后需要访问该变量以更改其值,如下所示:
var obj1= new cls(); //Two step method to initialize one value
obj1.str = "New value";
So it is always better and standard way to initialize variables in constructor this is the benefit of using object oriented programming language. 因此,在构造函数中初始化变量始终是一种更好的标准方法,这是使用面向对象编程语言的好处。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.