对象变量未在方法内更新

时间:2019-02-01 00:14:54

标签: typescript pass-by-reference

我正在尝试更新作为参数传递给我的打字稿代码中方法的对象,但是它永远不会改变:

export class MyClass {

  //...
  myMethod(array) {
    //...
    let myVariable: MyObject;
    array.forEach(currentElement => {
      if (someCondition) {
        this.replaceVariable(myVariable, currentElement);
      }
    });

    console.log(myVariable); // myVariable here is Undefined

    return myVariable;
  }

  private replaceVariable(variableToReplace: MyObject, newValue: MyObject) {
    if (variableToReplace == null) {
      variableToReplace = newValue;
    } else {
      if (someCondition) {
        variableToReplace = newValue;
      }
    }

    console.log(variableToReplace); // variableToReplace here is replaced by newValue
  }
}

由于对象总是通过引用传递的,因此我期望myVariable在调用方法replaceVariable之后会获得新值。但是正如您在代码注释中看到的那样,该变量在replaceVariable方法内部被替换,并在undefined中保留一个myMethod

0 个答案:

没有答案