0

I have an app which uses a custom defined generic class which always has the properties type and content but can represent a variety of different content types and must define generic methods for each type such as getContent, setContent, etc. To do this, I've defined the generic class as so in one file:

function Block(type) {
    this.type = type;
    this.content = "";

    switch(this.type){
        case "text":
            Object.setPrototypeOf(this, TextBlock);
            break;
        case "picture":
            Object.setPrototypeOf(this, PictureBlock);
            break
    }
}

and the respective prototypes in their own files like so:

// textblock.prototype.js

TextBlock = {

    createLine() {
        //
    },

    setContent() {
        //
    },

    //etc
}

When a new block is created with new Block("text"); the type, content, and prototype methods will be initiated. These prototype methods will only be set once with Object.setPrototypeOf() and will not be changed or reset throughout the execution of the code.

My question is: does using Object.setPrototypeOf() in this way significantly reduce performance? MDN has a warning on their page saying that using this method could have severe performance issues but I was wondering if anyone more knowledgeable on the subject could speak about when the appropriate use for this method would be. It is afterall a standard.

  • the warning is clear - MDN don't post warnings like that just for giggles :p - oh, and it's been asked (and answered) on stackoverflow before https://stackoverflow.com/questions/32444575/whats-the-performance-impact-of-setprototypeof-on-a-new-object – Jaromanda X Jul 12 '18 at 01:42
  • `.setPrototypeOf()` does not do what you think it does. (You're pretty much doing a Factory pattern ... use Object.create()) – Tibrogargan Jul 12 '18 at 01:43
  • @Tibrogargan thanks I searched and didn't find that. Using the object.assign() can I still use the `new Block("text")` syntax when creating a new Block object? – Alfredo Gonzalez Jul 12 '18 at 01:53
  • You could, but is there something special about it that you need to keep? `function blockFactory(type) { var templates = { "text": TextBlock, "picture": PictureBlock }; return Object.create(templates[type]) }` – Tibrogargan Jul 12 '18 at 02:33
  • @Tibrogargan I suppose it's one part that I have a few places where `new Block()` is called so a drop in replacement would be nice. Also, the rest of my objects in my project are created that way so readability would be nicer that way imo. Thanks for the example! – Alfredo Gonzalez Jul 12 '18 at 02:46

0 Answers0