打字稿-无法更新对象中的对象

时间:2020-07-12 18:55:56

标签: typescript object

我有一个Typescript对象,如下所示:

export class DocumentIndex {
  objectId: number;
  key = '';
  iconPath = '';
  searchParm: SearchParm = new SearchParm();

  constructor(public name: string, public description: string) {
    this.objectId = JsUtil.getObjectId();
  }
}

我的目标是更改SearchParm对象的值。 SearchParm对象的定义如下:

export class SearchParm {
  searchType = SearchType.none;
  searchTerm = '';
  constructor() {
  }
}

这是我尝试将searchTerm和searchType设置为另一个值的代码:

let docIndex = new DocumentIndex(searchValue, '');

docIndex.searchParm.searchTerm = searchValue; // searchValue is a string set to "G Triad"
docIndex.searchParm.searchType = SearchType.fullText; // this is a string set to "fullText"

console.log('documentIndex searchParm...', docIndex.searchParm);
console.log('documentIndex...', docIndex);

这是Chrome中的结果。请注意,SearchParm与原始设置保持不变。

Chrome result

这里会发生什么?我正在研究的其他地方使用了相同的代码,并且可以正常工作。

1 个答案:

答案 0 :(得分:0)

console.log(obj)用于某个对象obj时,您可能会认为它会在登录时将有关obj状态的某些信息记录到控制台。不能保证这是真的。浏览器经常会引用obj,每当您查看控制台时,您都会看到obj current 状态。因此,如果您在登录后修改obj,可能会感到困惑:

const obj = {foo: "bar"}; // empty
console.log(obj); // what gets logged here?  {foo: "bar"} or {foo: "baz"}?
obj.foo = "baz";

对于该代码,Firefox向我显示以下折叠/展开视图:

// collapsed view
// ▶ Object { foo: "bar" }

// expanded view
// ▼ {…}
//   foo: "baz"

因此,您不能真正依靠console.log()对对象引用的处理。相反,您可以考虑使用doing something like JSON.stringify(obj) before logging it。这样做的好处是可以在记录日志时捕获记录对象的至少某些状态:

const obj = {foo: "bar"}; // empty
console.log(JSON.stringify(obj)); // definitely logs {"foo":"bar"}
obj.foo = "baz";

对于您而言,我强烈怀疑您是在登录代码之后重新分配docIndex.searchParm。这很容易导致console.log(docIndex)显示其searchParm属性的当前值,而console.log(docIndex.searchParm)显示曾经是其{ {1}}属性:

searchParm

如果您使用docIndex.searchParm.searchTerm = searchValue; // searchValue is a string set to "G Triad" docIndex.searchParm.searchType = SearchType.fullText; // this is a string set to "fullText" console.log('documentIndex searchParm...', docIndex.searchParm); console.log('documentIndex...', docIndex); // this happens later docIndex.searchParm = new SearchParm(); // documentIndex searchParm... Object { searchType: "fullText", searchTerm: "G Triad" } // documentIndex... searchParm: ▼ {…} // Object { searchType: "none", searchTerm: "" } ,该问题应该会消失:

console.log(JSON.stringify())

好的,希望能有所帮助;祝你好运!

Playground link to code