Javascript 在类本身中初始化TypeScript变量和在构造函数中初始化TypeScript变量之间的区别
vs 这两种形式有什么区别?没有区别。这:Javascript 在类本身中初始化TypeScript变量和在构造函数中初始化TypeScript变量之间的区别,javascript,typescript,Javascript,Typescript,vs 这两种形式有什么区别?没有区别。这: class cls { str: string; constructor() { this.str = 'hello'; } } 将产生以下输出: class Foo { str = 'hello'; } class Bar { str: string; constructor() { this.str = 'hello'; } } 这里没有具体的区别。但是如
class cls {
str: string;
constructor() {
this.str = 'hello';
}
}
将产生以下输出:
class Foo {
str = 'hello';
}
class Bar {
str: string;
constructor() {
this.str = 'hello';
}
}
这里没有具体的区别。但是如果你写在下面:
var Foo = (function () {
function Foo() {
this.str = 'hello';
}
return Foo;
}());
var Bar = (function () {
function Bar() {
this.str = 'hello';
}
return Bar;
}());
然后在初始化类时,您可以将值分配给属性。
例如:
class cls {
str: string;
constructor(string str) {
this.str = str;
}
这在第一种情况下是不可能的。当您选择在构造函数中初始化变量时,在创建对象时初始化这些值会给您带来额外的好处,如下所示:
var obj1= new cls("obj1");
var obj2= new cls("obj2");
但当您没有在构造函数中初始化值时,则必须首先创建对象,然后需要访问该变量以更改其值,如下所示:
var obj1= new cls("obj1"); //Ability to change variable value
var obj2= new cls("obj2");
因此,在构造函数中初始化变量总是更好、更标准的方法这是使用面向对象编程语言的好处。第一种方法与调用super的默认构造函数一起工作,除此之外,没有区别。我删除了ES6标记,因为您的代码段都无效。ES6.str不是构造函数参数,因此答案不适用。
var obj1= new cls("obj1"); //Ability to change variable value
var obj2= new cls("obj2");
var obj1= new cls(); //Two step method to initialize one value
obj1.str = "New value";