2

When I'm declaring instance methods in JS I often use this syntax:

var MyObj = function (p1) {
    this.p1 = p1;    
};

MyObj.prototype = {
    method1: function() {},
    method2: function() {},
    method2: function() {}
};

Is there a similar way to declare "static" methods instead of doing this:

MyObj.static1 = function() {
};

MyObj.static2 = function() {
};

MyObj.static3 = function() {
};
gabric
  • 1,865
  • 2
  • 21
  • 32
  • 1
    Just a note, you don't wanna completely override the prototype, you might lose Object heritage for it; just assign each separately – casraf Aug 12 '15 at 09:09
  • 1
    You could use the same syntax that you used for the prototype definition, `MyObj = {static1 : function(){...}, }` – Hacketo Aug 12 '15 at 09:10
  • 2
    @Hacketo, that would turn the constructor function into a (non-callable) object literal. So I don't think you can do that. – Frédéric Hamidi Aug 12 '15 at 09:11
  • @FrédéricHamidi OP want to keep the "constructor" function ? Then static methods should be declared in an other namespace – Hacketo Aug 12 '15 at 09:11
  • @Hacketo, yes, they only want to add static methods. It is perfectly legitimate to have static methods as members of the constructor function instead of "another namespace". – Frédéric Hamidi Aug 12 '15 at 09:11
  • @FrédéricHamidi of course but OP want to avoid this way `MyObj.static3 = function() {};` – Hacketo Aug 12 '15 at 09:15
  • @Hacketo, indeed, that's why the solution is `Object.assign()` (if your target browsers support ES6), or `$.extend()` if you're into jQuery, or a polyfill of some sort (like in aduch's answer). – Frédéric Hamidi Aug 12 '15 at 09:16
  • I dislike modifying the `prototype` directly and prefer to do it all in the "constructor." Also, I think the *best* way for static methods is what you're already doing. – Purag Aug 12 '15 at 09:16
  • No support to ES6 and I'd like to aviod external libs of any sort. So I'll stick with the current syntax. I just wanted to make sure that there ins't a more concise way to declare them – gabric Aug 12 '15 at 09:18
  • Notice that even [for declaring prototype methods you shouldn't use this syntax](http://stackoverflow.com/q/17474390/1048572) – Bergi Aug 12 '15 at 09:25

1 Answers1

2

The only thing I can think of is doing it in two steps:

var staticMethods = {
    static1: function () {
    },
    static2: function () {
    },
    static3: function () {
    }
};

Then use this function

function registerStaticMethods(aClass, staticMethods) {
    for (var methodName in staticMethods) {
        aClass[methodName] = staticMethods[methodName];
    }
}

You would use it like this

registerStaticMethods(MyObj, staticMethods);
axelduch
  • 10,769
  • 2
  • 31
  • 50