0

When I read JavaScript The Definitive Guide, section 9.3, I encountered this:

Class methods
These are methods that are associated with the class rather than with instances.

How do I implement class methods in JavaScript?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
yuan
  • 2,434
  • 1
  • 21
  • 29
  • If, by "class" you mean constructor function, then yes, just define methods on the constructor. – Šime Vidas Dec 11 '12 at 15:38
  • So, what does the term "class" refer to? – Bergi Dec 11 '12 at 15:38
  • @Šime Vidas: Not on the constructor, on the constructor prototype. – Ryan Lynch Dec 11 '12 at 15:39
  • Probably a duplicate of this question: http://stackoverflow.com/questions/4305578/best-practices-for-static-methods-and-variables-with-mootools-classes – AlexStack Dec 11 '12 at 15:39
  • @RyanLynch Methods defined on the constructor's prototype are *not* class methods, but instance methods. OP is asking about class methods, not instance methods. – Šime Vidas Dec 11 '12 at 15:40
  • Ah, misunderstood the question. Adding methods on the constructor is the method used by various libraries to simulate class methods, but as with all things related to classes in JavaScript it is just a pattern that you can choose to use. – Ryan Lynch Dec 11 '12 at 15:43

1 Answers1

4

You can just create a function as a property of another function:

function MyClass() {
}

MyClass.someFunction = function() { };
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • 1
    Since JavaScript currently doesn't have a true OOP model the above is the equivalent of a static or class method, static or class properties can be defined in a similar fashon MyClass.someProperty = "myValue"; On a similar note instance methods are defined on the prototype property of objects so MyClass.prototype.someFunction = function() { }; is an instance method and MyClass.prototype.SomeProperty = "someValue"; is an instance property. These aren't the only ways to declare these types of functions and properties you can search for Object Oriented JavaScript to find more examples. – HJ05 Dec 11 '12 at 16:02