0

I was curious what happens when you try to alter an object retrieved through a class getter

class A {
    constructor () {
        let props = { foo: { hello: 'world' } };

        Object.defineProperty(this, 'foo', {
            get: () => props.foo
        });
    }
}

let a = new A();
    a.foo; // { hello: 'world' }
    a.foo.hello = 2;

    a.foo.hello === 2; // true or false?
neaumusic
  • 10,027
  • 9
  • 55
  • 83
  • 3
    Why would you expect this to be any different from any other way of retrieving an object? Objects aren't copied when you retrieve them. – Barmar Oct 29 '16 at 22:05
  • @Barmar Because nowadays you don't know what restrictions the compiler is going to put in, you should be ashamed of your snarky question – neaumusic Oct 31 '16 at 21:47
  • Compilers don't put arbitrary restrictions on you. In general, statements just do what you tell them to. In Javascript, assigning objects doesn't make copies of them, it assigns references. – Barmar Oct 31 '16 at 21:48
  • @Barmar Bro, obviously objects are passed by reference, ridiculous that you think I can write JS like this and don't know that. The reason I'm asking is because it's a getter and there is no attached setter. Hence why I'm asking the question – neaumusic Oct 31 '16 at 22:35
  • And they do put restrictions on you, like not being able to set a property on an object that only has a getter for that prop. Or not being able to set a default value when both get and set are defined – neaumusic Oct 31 '16 at 22:36

1 Answers1

0

Altering properties in the returned object reference will alter the instance's object reference as well

class A {
    constructor () {
        let props = { foo: { hello: 'world' } };

        Object.defineProperty(this, 'foo', {
            get: () => props.foo
        });
    }
}

let a = new A();
    a.foo; // { hello: 'world' }
    a.foo.hello = 2;

    a.foo.hello === 2; // true

Only the directly returned value is immutable and assignment won't change the instance's prop val:

a.foo = 'noob'; 
a.foo === 'noob'; // false

neaumusic
  • 10,027
  • 9
  • 55
  • 83