Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/401.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在构造函数内部和外部声明类成员变量的Typescript_Javascript_Typescript_Class - Fatal编程技术网

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);

啊,我明白了-所以存储需要在外部初始化,它的实例插入到第二个案例中。谢谢,这有助于我理解它!