Vitaly Zdanevich
Vitaly Zdanevich

Reputation: 14876

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);

As I understand this is impossible, but maybe some trick exists?

Upvotes: 0

Views: 41

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075219

No, you can't do that.

Instead, your best bet is to return the new object, and reassign when calling:

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

fetch = f(fetch);

Alternately, you can pass in a container that has the target object as a part of its state, and update the state of that container:

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

or

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

Upvotes: 2

Related Questions