13
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?

3 Answers 3

12

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.

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

10 Comments

Why would inst have a method sum in your usage case? Wouldn't you need something like sum.call(inst)?
Also, on the "why not?" question - because it makes your code hard to read and reduces code compression.
sum is "static" in nature -- it doesn't really care about this. There is absolutely no need to use call in this case.
Right, but my point is that, unless I'm missing something, inst doesn't have a property named sum - it only has a property named staticMethod. Is that what you meant?
@nrabinowitz "Hard to read" is subjective. It all depends on the conventions and contracts that you define. Remember, these classical inheritance, privates/publics/statics etc. are all non-JavaScript-native.
|
1
 ( function (fn) {
     fn.bar = function (...) { ... } ;
     ...
 } ) ( Foo.prototype ) ;

In other word, you create an anonymous function that will populate the prototype of Foo.

Comments

0

You can create a static method within the constructor function, but only by using the same syntax:

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

But this would only add the static method once the constructor is called. Also, it would re-add it every additional time the constructor is called, which seems wasteful, but I guess could be useful, e.g.:

function Foo() {
    var counter = (Foo.bar && Foo.bar() || 0) + 1;
    Foo.bar = function (){
        return counter;
    };
}

f = new Foo();
Foo.bar(); // 1
f2 = new Foo();
Foo.bar(); // 2

In this case, bar is updated to return the number of times Foo has been called - probably there's a reasonable variant here that could keep track of all instances in a useful way.

If you really didn't want to refer to Foo for some reason, you could be clever and do something like this:

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

Again, this only works after Foo has been called at least once. Also, while this does demonstrate an alternative syntax, I'm having a really hard time imagining when you might want to use it.

Yet another variation here, probably equally useless:

function Foo() {
    this.constructor.bar = function (){
        console.log("test");
    };
}

6 Comments

Getting "TypeError: Foo.bar is not a function".
@osoviejo - yes, see my update - this only works after you've called the constructor at least once. There's no way to do something inside a constructor function that will take effect before the function runs.
There is nothing "static" about requiring a initial instance :(
@AtesGoral - well, not in the classical sense. But it's a standalone method attached directly to the constructor function, which is as close as Javascript gets to "static" anyway.
@nrabinowitz True true... But in any case, it is more natural to attach it outside the constructor, just like the OP has in their example. Perhaps the answer to the OP's question is a simple "no, that's the only way".
|

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.