Blog

  • Home /
  • Blog /
  • Basic JavaScript Part 7: Static Properties and Methods

Basic JavaScript Part 7: Static Properties and Methods

January 19, 2011

Here are the links to the previous installments:

  1. Functions
  2. Objects
  3. Prototypes
  4. Enforcing New on Constructor Functions
  5. Hoisting
  6. Automatic Semicolon Insertion

In this post, I’m going to quickly show you how to set up static properties and methods in JavaScript. This can come in handy for constant values and/or utility functions. C# and most other class-based languages have a special syntax for static members. Not so for JavaScript. Although JavaScript doesn’t provide a dedicated syntax for static members, we’re still able to get what we want by adding properties and methods to a constructor function. This is possible because functions in JavaScript are plain objects that can have properties and methods of their own. 

Let’s show some code.

Here we created a constructor function named Podcast with a static property called FILE_EXTENSION and a static method named download. We also added the instance method play() to the prototype of our constructor function.

Getting the value of a static property or invoking a static method is done as follows:

When we create a Podcast object and invoke the instance method play(), we obviously get the expected outcome.

But it’s surely not possible to statically invoke an instance method like so:

It’s also not possible to invoke a static method on a Podcast instance object either.

function Podcast() {};

Podcast.FILE_EXTENSION = 'mp3';
Podcast.download = function(podcast) {
    console.log('Downloading ' + podcast + ' ...');
};

Podcast.prototype.play = function() {
    console.log('Playing this podcast ...');
};

There you go. Knowing how to provide static members in JavaScript might come in handy when you feel inspired of writing your own Math class in JavaScript :-).

Until next time.

If you and your team want to learn more about how to write maintainable unit tests and get the most out of TDD practices, make sure to have look at our trainings and workshops or check out the books section. Feel free to reach out at infonull@nullprincipal-itnull.be.

Profile picture of Jan Van Ryswyck

Jan Van Ryswyck

Thank you for visiting my blog. I’m a professional software developer since Y2K. A blogger since Y2K+5. Provider of training and coaching in XP practices. Curator of the Awesome Talks list. Past organizer of the European Virtual ALT.NET meetings. Thinking and learning about all kinds of technologies since forever.

Comments

About

Thank you for visiting my website. I’m a professional software developer since Y2K. A blogger since Y2K+5. Author of Writing Maintainable Unit Tests. Provider of training and coaching in XP practices. Curator of the Awesome Talks list. Thinking and learning about all kinds of technologies since forever.

Contact information

(+32) 496 38 00 82

infonull@nullprincipal-itnull.be