osoviejo osoviejo - 25 days ago 9
Javascript Question

static method patterns for constructor functions in javascript

function Foo(){...}
Foo.bar = function (){...};


Is this the only pattern for adding a static method to a constructor function? In particular, is it not possible to create the static method bar() within the definition of Foo() itself?

Answer

When you say "inside", it sounds like you need a clean way to keep everything in one place. You could potentially use a class inheritance library that has support for static declarations. Or simply take one and extend it yourself to add that capability.

For a simple (but not so compact) way to keep everything together, you could go with something like this:

var Foo = (function () {
    var ctor = function () {
        // the constructor
    };

    ctor.staticMethod = function () {
        // something static
    };

    return ctor;
})();

But! How important really is making the declaration self-evident that it is static? You could simply declare your static methods as prototype methods and convey the fact that they are static (i.e. not acting on the instance) methods with some code comments. There won't be any contractual enforcement of how these methods are invoked, but there will be few side-effects. So I would just go with:

function Foo() {
    // the constructor
    // optionally define instance methods here
}

Foo.prototype = {
    instanceMethod: function () {
        // some instance method
        // this.bar(); ...
    },
    staticMethod: function () {
        // some static method
        // return 2 + 3;
    }
};

Usage:

// Using "prototype" explicitly can be your contract for saying "this is static"
var sum = Foo.prototype.staticMethod();

var inst = new Foo();

var sum2 = inst.staticMethod(); // You have the added benefit of being able to call your static methods on instances

I've found that the above comes in handy especially when you're using the factory design pattern. Your class can have some static factory methods in its prototype and you can invoke these factory methods even when you only have an instance whose origin class you don't know.

Comments