Typescript 对象变量为';t在方法内部更新

Typescript 对象变量为';t在方法内部更新,typescript,pass-by-reference,Typescript,Pass By Reference,我正在尝试更新typescript代码中作为参数传递给方法的对象,但它从未更改: export class MyClass { //... myMethod(array) { //... let myVariable: MyObject; array.forEach(currentElement => { if (someCondition) { this.replaceVariable(myVariable, currentE

我正在尝试更新typescript代码中作为参数传递给方法的对象,但它从未更改:

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
方法中被替换,并在
myMethod

由于对象总是通过引用传递,所以我希望myVariable在调用replaceVariable方法后获得新值

是的,它们是通过引用传递的。然而,它们不是作为变量传递的。你可以变异,但不能重新分配

差别 由于JavaScript不支持out变量,因此下面是这两个变量的C#参考,您可以理解它们之间的区别:

  • 参考号
  • 出去

谢谢您的解释。最后,我从
replaceVariable
方法返回值,并将其分配给变量实例
myVariable
Perfect choice