是否有可能以某种方式替换作为函数参数的原始对象?
Is it possible somehow to replace original object that is argument to a function?
function f(obj) {
obj = _ => console.log(
'LOCAL object was replaced, how to replace from the outer scope?');
}
f(fetch);
据我所知,这是不可能的,但也许存在一些技巧?
不,你不能那样做。
相反,您最好的选择是 return 新对象,并在调用时重新分配:
function f(obj) {
return _ => console.log(
'LOCAL object was replaced, how to replace from the outer scope?');
}
fetch = f(fetch);
或者,您可以传入将目标对象作为其状态的一部分的容器,并更新该容器的状态:
function f(container) {
container.obj = _ => console.log(
'LOCAL object was replaced, how to replace from the outer scope?');
}
var c = {obj: fetch};
f(c);
// ...use c.obj...
或
function f(container) {
container[0] = _ => console.log(
'LOCAL object was replaced, how to replace from the outer scope?');
}
var c = [fetch];
f(c);
// ...use c[0]...
function f(obj) {
obj = _ => console.log(
'LOCAL object was replaced, how to replace from the outer scope?');
}
f(fetch);
据我所知,这是不可能的,但也许存在一些技巧?
不,你不能那样做。
相反,您最好的选择是 return 新对象,并在调用时重新分配:
function f(obj) {
return _ => console.log(
'LOCAL object was replaced, how to replace from the outer scope?');
}
fetch = f(fetch);
或者,您可以传入将目标对象作为其状态的一部分的容器,并更新该容器的状态:
function f(container) {
container.obj = _ => console.log(
'LOCAL object was replaced, how to replace from the outer scope?');
}
var c = {obj: fetch};
f(c);
// ...use c.obj...
或
function f(container) {
container[0] = _ => console.log(
'LOCAL object was replaced, how to replace from the outer scope?');
}
var c = [fetch];
f(c);
// ...use c[0]...