我正在使用 ES6 和 Angular2。在构造函数中声明以下内容有什么区别:
class Example{
constructor(private one: SomeClass, two: SomeClass){
this.two = two;
}
}
像这样:
class Example2{
private three:String = `What's the difference?`
}
到目前为止,我明白如果我导入一个类,那么我必须通过构造函数声明它。这里的一
、二
和三
有什么区别?
最佳答案
构造函数中的代码将在创建对象实例时执行。类中但构造函数外部的代码成为类使用的类字段/成员,或者可以在创建实例后调用。
在你的例子中。 one
和 two
是实例化类时预期传递到构造函数的参数名称。这些值必须传递给构造函数。
三
是一个类“field”。它由类创建并在类的生命周期内私有(private)使用。它没有传递到类中。
例如,这样:
class Example{
constructor(private one: SomeClass, two: SomeClass){
this.two = two;
}
}
你可以像这样实例化它:
var someClass1 = new SomeClass();
var someClass2 = new SomeClass();
var myExample = new Example(someClass1, someClass2);
但在这种情况下:
class Example2{
private three:String = `What's the difference?`
}
你只需实例化如下:
var myExample2 = new Example2();
关于javascript - 构造函数内声明和构造函数外部声明的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41983492/