Senica Gonzalez
Senica Gonzalez

Reputation: 8192

Javascript reassign variable and not break reference

Assuming the following:

let __somevar__ = { hi: 'john' };
Object.defineProperty(window, 'somevar', {
    set: (value)=>{
        __somevar__ = value;
    },
    get: ()=>{
        return __somevar__;
    }
})

let newvar = window.somevar;

// Is it possible to keep the window.somevar reference so that is always uses the setters/getters?
// obviously this actually reassigns newvar instead of using the window.somevar setter.
newvar = { hi: 'senica' }

// These are different now.
console.log(newvar, window.somevar);

// Object.assign won't work because getters/setters are not enumerable.

// A proxy would work, but that's not my question.

Not super important...was just curious.

Thanks!

Upvotes: 2

Views: 84

Answers (2)

MinusFour
MinusFour

Reputation: 14423

Like I said in the comment, can be done with Object.defineProperty, just not with =:

let __somevar__ = { hi: 'john' };
Object.defineProperty(window, 'somevar', {
    set: (value)=>{
        __somevar__ = value;
    },
    get: ()=>{
        return __somevar__;
    }
})

Object.defineProperty(window, 'newvar', Object.getOwnPropertyDescriptor(window, 'somevar'))

newvar = { hi: 'senica' }

console.log(newvar === window.somevar);

Upvotes: 3

WuDo
WuDo

Reputation: 195

This code:

let newvar = window.somevar;

the newvar will contains refrence to somevar.

With

newvar = { hi: 'senica' };

You do override newvar value (the reference) to the new object. That doesn't do anything with somevar.

Upvotes: 0

Related Questions