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