18

Does JSON.stringify work with objects that are created like

obj = {}
Object.defineProperty(obj, 'prop', {
  get: function() { return 1 }
  set: function(value) { ... }
})

It returns {} when called on this object.

1

1 Answer 1

38

You might want to set the enumerable option to true, like this:

Object.defineProperty(o, 'test', {
    get: function () { return 1; },
    enumerable: true
});
Sign up to request clarification or add additional context in comments.

5 Comments

I don't know why they didn't make enumerable:true the default. It was causing me quite the headache when I tried to convert to JSON.
That works fine with object not not classes :(
@MatthieuRiegler Well, class instances are just objects. You could call the above code on this in the class's constructor.
Yeah that's what I just found out (I was using the prototype), thx !
@MatthieuRiegler Note that you can still reuse the same function instance rather than creating a new one inline.

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.