0

I need to be able to serialize an object declared with a class in ECMA6 . I could use toJSON easily when using standard JavaScript to get and serialize the "methods" stored in the prototype.

var Foo = function(name) {
    this.name = name;
}
Foo.prototype = { 
    doSomething: function() {
        return 1;
    },
    toJSON: function() {
        // construct a string accessing Foo.prototype
        // in order to get at functions etc. stored in prototype...
    }  
};

But how do I do this using class declarations in ECMA6? Example:

class Foo {
    constructor(name) {
        this.name = name;
    }   
    doSomething() {
        return 1;
    }   
    toJSON() {
        // Foo.prototype is empty. Because it hasn't been created yet?
    }
}

Even after instantiation with the new operator, objects created with class seem to have an empty prototype. What am I missing?

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Aaron
  • 3,249
  • 4
  • 35
  • 51
  • Please fix the formatting of your code. It's not like you're a new user. –  Oct 06 '16 at 14:10
  • As an alternative to serialising the objects wholesale, you could just serialise all the data they need and then re-create them using the stored data. – VLAZ Oct 06 '16 at 14:12
  • 4
    If you need to stringify the methods, and then parse them back later, you're probably doing something you shouldn't be doing. – adeneo Oct 06 '16 at 14:14
  • @vlaz, that would probably work. With the disadvantage obviously that I'd have to explicitly access the function name. – Aaron Oct 06 '16 at 14:39

1 Answers1

1

What you are doing sounds like a bad idea; but at any rate, class methods are in the prototype; they just are not enumerable, to avoid having them showing up in for .. in iteration (and also probably to prevent things like what you are trying to do from being easy to do). You would have to use Object.getOwnPropertyNames and Object.getOwnPropertySymbols.

Jessidhia
  • 514
  • 4
  • 7
  • It may be a bad idea. I am doing it because PhantomJS only allows things that are JSON serializable to be passed in to `page.evaluate`. I have a module of test objects that get run on a page opened by PhantomJS and that need to get passed in to `evaluate` and deserialized once inside PhantomJS's `page.evaluate`s scope. The idea behind sandboxing `page.evaluate` is to keep the scope of the page and the phantomjs script separate, but `page.evaluate` does allow passing in simple data, so they obviously found that there are valid use-cases. – Aaron Oct 06 '16 at 14:26
  • I still can't get this to work. It returns an array of property names but seems to skip properties with functions as values. – Aaron Oct 06 '16 at 14:40