首页 > 解决方案 > 在不同的 TypeScript 类之间共享和改变对象

问题描述

我有以下打字稿代码:

class ClassA {
    options: ClassOption;
    B: ClassB;

    constructor() {
        this.B = new ClassB(this.options);
        this.changeOptions();
    }

    changeOptions(): void {
        const newOptions: ClassOption = new ClassOption("something");
        this.options = newOptions;
    } 
}

class ClassB {
    options: ClassOption;

    constructor(opts: ClassOptions) {
        this.options = opts;
    }

    someFunction(): ClassOption {
        return this.options;
    }
}

问题是当我实例化时ClassA

const a = new ClassA();

a.B.someFunction();返回undefined而不是从ClassA'schangeOptions方法设置的新选项。

标签: javascriptangulartypescriptreferencees6-class

解决方案


当在ClassA's 构造函数中时,你会:

this.B = new ClassB(this.options);

this.options仍然是undefined,所以基本上在ClassB你的构造函数中时:

this.options = opt;

您只是设置this.optionsundefined而不是为其分配对ClassA's的引用options,因为它尚未初始化,所以它不存在。

即使您使用空对象进行初始化,如果您为其分配 ( options)一个新值,也不会引用新值。ClassAthis.options = somethingClassB

你想要做的是:

  1. 用空对象初始化ClassA's :this.options

    options: ClassOption = {};
    
  2. 将其传递给ClassB的构造函数。此处无需更改。

  3. 调用时ChangeOptions改变同一个对象,而不是用一个新对象替换它。您可以使用Object.assign合并两个对象:

    changeOptions(): void {
        const newOptions: ClassOption = new ClassOption("something");
        Object.assign(this.options, newOptions);
        // Note that after this, `this.options`' reference is preserved.
    } 
    

在这里你可以看到它在纯 JavaScript 中工作:

class ClassA {
   constructor() {
      // 1. Initialise with an empty object:
      this.options = {};
      
      // 2. Pass that reference to ClassB instead of undefined:
      this.B = new ClassB(this.options);
      
      this.changeOptions();
   }
   
   changeOptions() {
      // 3. Mutate this.options without changing its reference:
      Object.assign(this.options, {
        opt1: 1,  
        opt2: 2, 
      });
      
      // 3. You can also do it like this:
      this.options.opt3 = 3;
   } 
}

class ClassB {
   constructor(options) {
      this.options = options;
   }
   
   getOptions() {
      return this.options;
   }
}
 
const a = new ClassA();

a.changeOptions();

console.log(a.B.getOptions());


推荐阅读