Javascript 在构造函数内部和外部声明类成员变量的Typescript
在声明类成员时,使用Javascript 在构造函数内部和外部声明类成员变量的Typescript,javascript,typescript,class,Javascript,Typescript,Class,在声明类成员时,使用new关键字在构造函数内部和外部实例化一个类成员有什么区别 假设我有一个叫做“存储”的类。我不确定以下两者之间的区别: 类父类{ 私有只读存储=新存储(); } 类父类{ 构造函数(专用只读存储:存储){ } } 第一个示例将始终将存储设置为新存储(),而第二个示例要求新父级()的调用方在第一个参数中向构造函数提供存储 第一个示例与此等效: class Parent { // TS can infer the type of storage private read
new
关键字在构造函数内部和外部实例化一个类成员有什么区别
假设我有一个叫做“存储”的类。我不确定以下两者之间的区别:
类父类{
私有只读存储=新存储();
}
类父类{
构造函数(专用只读存储:存储){
}
}
第一个示例将始终将存储设置为新存储()
,而第二个示例要求新父级()的调用方在第一个参数中向构造函数提供存储
第一个示例与此等效:
class Parent {
// TS can infer the type of storage
private readonly storage;
constructor() {
this.storage = new Storage();
}
}
// parent.storage is set to new Storage()
const parent = new Parent();
class Parent {
private readonly storage;
constructor(storage: Storage) {
this.storage = storage;
}
}
declare const someOtherStorage: Storage;
// parent.storage is set to someOtherStorage, not necessarily from new Storage()
const parent = new Parent(someOtherStorage);
鉴于第二种情况相当于:
class Parent {
// TS can infer the type of storage
private readonly storage;
constructor() {
this.storage = new Storage();
}
}
// parent.storage is set to new Storage()
const parent = new Parent();
class Parent {
private readonly storage;
constructor(storage: Storage) {
this.storage = storage;
}
}
declare const someOtherStorage: Storage;
// parent.storage is set to someOtherStorage, not necessarily from new Storage()
const parent = new Parent(someOtherStorage);
啊,我明白了-所以存储需要在外部初始化,它的实例插入到第二个案例中。谢谢,这有助于我理解它!