1

Short version

Given the following class:

class Foo {
    constructor() {
        throw new Error("No!")
    }

    // ... more functions ...
}

How can I get an instance of Foo?

Explanation

The class actually looks like more this:

const KEY = Symbol("BAR")
function validateBarData(input) { 
    /* throws error if input is not in the format: */
    /* {name: "string", bartender: "string", drinks: [ "string" ]} */
}
class Bar {
    constructor(name, bartender, drinks) {
        this[KEY] = {name: name, bartender: bartender, drinks: drinks}
        // now validate to protect against garbage input like
        //   'name = 42' or 'drinks = undefined', etc.
        validateBarData(this[KEY])
    }

    encode() {
        return this[KEY]
    }

    static decode(data) {
        validateBarData(data)
        return new Bar(data.name, data.bartender, data.drinks)
    }

    // ... more functions ...
}

encode() and Bar.decode(data) are used to serialize state to something JSON.stringifyable so the object can be recreated later. The actual encode/decode logic here may be more complex than just 'dump this[KEY]' (e.g. encoding objects managed by the Bar object).

Problems when decoding:

  • validateBarData is called twice
  • Although we already have a valid internal state to assign to this[KEY] after the first line of decode, it first has to be destructured then recreated.

I'd like to avoid this duplication, but I've not been able to find the right way to do it.

How can I do this please?

1 Answer 1

1

Oops.

let foo = Object.create(Foo.prototype)

or

static decode(data) {
    validateBarData(data)
    let bar = Object.create(Bar.prototype)
    bar[KEY] = data
    return bar
}

Seconds before posting the question I tried one last thing, and it turns out I should have been calling Object.create on the prototype, not the class itself. How embarrassing...

I'm posting anyway because the keywords in the question title weren't showing up in search results (at time of writing; lots about java, but not javascript), so maybe this'll save someone else time in future.

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

Comments

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.