2

I know Javascript doesn't have classes in the same way that traditional OOP languages do and that a "class" definition such as the following, is merely a function object that can be used with the new keyword:

function MyClass(){
  this.a = function(){ /* Do something */ }; // Public function
  function b(){ /* Do something */ }; // Private function
}

What I'm wondering is, if I define a global object (to avoid polluting the namespace) and define my classes inside this object, can I define a static method for my class in a nicer way than this:

var MyObject = {
  MyClass: function(){
    this.a = function(){ /* Do something */ }; // Public function
    function b(){ /* Do something */ }; // Private function
  },
}
MyObject.MyClass.MyStaticMethod = function(){ /* Do something */ };

I was thinking something along the lines of defining MyStaticMethod inside the MyClass function scope - is this possible?

1 Answer 1

1

You can do this:

var MyObject = {
    MyClass: function(){
        this.a = function(){ /* Do instance-y stuff */ };
        MyClass.MyStaticMethod = function(){ /* Do static-y stuff */ };
    }
}

but I think it's a bad idea. In general, I think it's better practice (because it's more readable) to define both static and instance methods OUTSIDE of the constructor. As in:

function MyClass() { /* Do initialization stuff */ }
MyClass.prototype.a = function() { /* Do instance-y stuff */ }
MyClass.MyStaticMethod = function() { /* Do static-y stuff */ }
Sign up to request clarification or add additional context in comments.

Comments

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.