gpt4 book ai didi

javascript - 是否有可能以某种方式替换作为函数参数的原始对象?

转载 作者:行者123 更新时间:2023-12-01 01:38:29 25 4
gpt4 key购买 nike

function f(obj) {
obj = _ => console.log(
'LOCAL object was replaced, how to replace from the outer scope?');
}

f(fetch);

据我了解这是不可能的,但也许存在一些技巧?

最佳答案

不,你不能这样做。

相反,最好的选择是返回新对象,并在调用时重新分配:

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]...

关于javascript - 是否有可能以某种方式替换作为函数参数的原始对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52629893/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com