typescript 打字稿有没有办法通过引用将参数传递给方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35606970/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
typescript is there a way to pass parameter to method by reference?
提问by C.Frank
I have method that gets parameters and in this method there are calculations that change the parameters value. When returning from the method the parameters continue to other methods for more calculations.
我有获取参数的方法,在这个方法中有改变参数值的计算。从方法返回时,参数会继续到其他方法进行更多计算。
Is there a way to pass parameter to method by reference or the only way is by i join the parameters to object and return them?
有没有办法通过引用将参数传递给方法,或者唯一的方法是将参数加入对象并返回它们?
回答by Martin
With JavaScript, and TypeScript, you can pass an object by reference -- but not a value by reference. Therefore box your values into an object.
使用 JavaScript 和 TypeScript,您可以通过引用传递对象——但不能通过引用传递值。因此,将您的值装箱到一个对象中。
So instead of:
所以而不是:
function foo(value1: number, value2: number) {
value1++;
value2++;
}
Do:
做:
function foo(model: {property1: number; property2: number}) {
model.property1++;
model.property2++;
// Not needed but
// considered good practice.
return model;
}
const bar = { property1: 0, property2: 1 };
foo(bar);
console.log(bar.property1) // 1
console.log(bar.property2) // 2