gpt4 book ai didi

javascript - 构造函数内声明和构造函数外部声明的区别

转载 作者:行者123 更新时间:2023-12-01 04:03:39 25 4
gpt4 key购买 nike

我正在使用 ES6 和 Angular2。在构造函数中声明以下内容有什么区别:

class Example{
constructor(private one: SomeClass, two: SomeClass){
this.two = two;
}
}

像这样:

class Example2{
private three:String = `What's the difference?`
}

到目前为止,我明白如果我导入一个类,那么我必须通过构造函数声明它。这里的有什么区别?

最佳答案

构造函数中的代码将在创建对象实例时执行。类中但构造函数外部的代码成为类使用的类字段/成员,或者可以在创建实例后调用。

在你的例子中。 onetwo 是实例化类时预期传递到构造函数的参数名称。这些值必须传递给构造函数。

另一方面,

是一个类“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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com