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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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:
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:
Usage:
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.