Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Design question: Polymorphism in javascript

Tags:

javascript

I'm trying to design an easily extendable form system in javascript, but am having some issues laying it out.

Imagine a web form where you could fill in recipes, put them in some order, and then submit them for a chef to cook. Then, let's say you have 3 classes of recipes: salad, appetizers, and main course. Obviously each form will have a different number of fields and different forms.

What I'm trying to do is have one overall form manager that essentially takes in a base class Recipes and calls various things on it, like .saveForm(), .fillForm(), or createNewForm() but I'd like each of these things to be implemented in the derived classes.

What is the best way to go about implementing this OO structure in Javascript? Or is this not the correct way to do it? After writing a bit of code, I found myself assigning my own types and constantly doing manual type checking, but this makes it harder to extend.

like image 517
victor Avatar asked Nov 06 '22 01:11

victor


1 Answers

Here is what I would do:

var Class = function (Parent, props) {
    var Child, F, i;

    Child = function () {
        if (Child.uber && Child.uber.hasOwnProperty("__construct")) {
            Child.uber.__construct.apply(this, arguments);
        }
        if (Child.prototype.hasOwnProperty("__construct")) {
            Child.prototype.__construct.apply(this, arguments);
        }
    };

    Parent = Parent || Object;
    F = function () {};
    F.prototype = Parent.prototype;
    Child.prototype = new F();
    Child.uber = Parent.prototype;
    Child.prototype.constructor = Child;

    for (i in props) {
        if (props.hasOwnProperty(i)) {
            Child.prototype[i] = props[i];
        }
    }

    return Child;
};

var Recipe = Class(null, {
    __construct: function (name) {
        this.name = name;
    },
    getName: function () {
        return this.name;
    }
});

var Salad = Class(Recipe, {
    __construct: function (name) {
        this.name = name;
    },

    getName: function () {
        var name = Salad.uber.getName.call(this);
        return name;
    }
});

So in this example, we use the Class function to fake a more structured object-oriented approach than what is normally available in javascript.

We define the Recipe class with a constructor and an example method. We then create the Salad class which inherits the properties and methods of the Recipe class, and then we redefine the getName method. Inside that method, we use a static property to access the parent classes implementation of that method.

This code is based on the examples presented in "JavaScript Patterns" by Stoyan Stefanov if you wanted to read more about it.

like image 109
Jason Miesionczek Avatar answered Nov 13 '22 15:11

Jason Miesionczek