0

I have this code:

class Obj {
    constructor() {
        this.foo = "foo";
    }
}

Object.defineProperty(Obj.prototype,'foo',{enumerable:false,writable:true});
Object.defineProperty(Obj,'foo',{enumerable:false,writable:true});

let obj = new Obj();

console.log(obj);

And my output is:

Obj { foo: 'foo' }

The problem is, I defined the enumerable property as false for foo. But when in the construct I use 'this.foo' that property change it.

I know I can put in the constructor:

Object.defineProperty(this,'foo',{enumerable:false,writable:true});

And my new output throws correctly:

Obj {}

But, my question is if is possible to change once the property of foo and not change it in the constructor?

Thanks!

2
  • what are you trying to achieve? Commented Sep 16, 2017 at 16:07
  • I trying to change the properties of an object only one time. And not changing when I create a new object Commented Sep 16, 2017 at 16:13

1 Answer 1

1

my question is if is possible to change once the property of foo and not change it in the constructor?

The short answer: No.

That's because every time the constructor is called and this.foo = "foo"; is executed, you are creating a new property. The properties you create on Obj.property and Obj are completely irrelevant actually. They are completely separate properties, defined on different objects, not this.

Just look at Obj and obj more closely:

enter image description here

You can see three different foo properties and I noted which operations create them. Hopefully this makes it clearer why setting the enumerability of Obj.foo or Obj.prototype.foo has no influence on obj.foo.


this.foo = "foo"; creates an enumerable property. If you don't want it to be enumerable then you have to create it with Object.defineProperty instead. Again, the properties you create on Obj and Obj.prototype have nothing to do with the one you create on this.

Sign up to request clarification or add additional context in comments.

2 Comments

So, the best case is: change the properties in the constructor?
Yes, you have to create the property exactly how you want it. As I said, Obj.foo, Obj.prototype.foo and this.foo are three completely separate properties.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.