【问题标题】:Is it possible somehow to replace original object that is argument to a function?是否有可能以某种方式替换作为函数参数的原始对象?
【发布时间】:2018-10-03 14:54:05
【问题描述】:
function f(obj) {
    obj = _ => console.log(
        'LOCAL object was replaced, how to replace from the outer scope?');
}

f(fetch);

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

【问题讨论】:

    标签: javascript pass-by-reference


    【解决方案1】:

    不,你不能那样做。

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

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

    【讨论】:

      猜你喜欢
      • 2018-07-25
      • 2015-12-07
      • 1970-01-01
      • 1970-01-01
      • 2017-08-18
      • 1970-01-01
      • 2011-01-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多