【发布时间】:2019-02-01 00:14:54
【问题描述】:
我正在尝试更新作为参数传递给我的打字稿代码中的方法的对象,但它永远不会改变:
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 后获得新值。但正如您在代码 cmets 中看到的那样,变量在 replaceVariable 方法内被替换,并在 myMethod 中保留 undefined 值
【问题讨论】:
标签: typescript pass-by-reference