“Static” methods

Published Wed, Aug 26 2009 15:24

Today I was discussing some JS stuff with Nuno on twitter and I noticed that I still haven’t talked about“static” methods in JavaScript. We’ve learned several important things about functions. We’ve already seen that they are objects and that they can be used as constructors. We’ve even seen that they can me used as “instance” methods of your new objects. In this post, we’ll see how to create “static” methods.

Static methods are defined as properties of a function which (supposedly) is used as a constructor of a type. Here’s a small example:

var User = function(name, age) {
    this.name = name;
    this.age = age;
}
User.isEmpty = function(user) {
    return user == null ||
           user.name === null ||
           user.name === undefined ||
           user.name === "";
}
var user = new User("luis");
alert(User.isEmpty(user));

As you can see, the only way to access the isEmpty “static” method is through the User function. Calling these functions “static” methods is just a reminiscent of traditional OO programming. In fact, they’re nothing more than properties of the User function (this does make sense when you recall that functions are objects too!). The biggest advantage of using this “hack” is that you won’t be polluting the global namespaces with new functions (something which is really important if you’re building reusable libraries).

And that’s it. Keep tuned for more on JavaScript.

Filed under:

Leave a Comment

(required) 
(required) 
(optional)
(required) 
If you can't read this number refresh your screen
Enter the numbers above:  

Search

This Blog

Tags

Community

Archives

Syndication

Email Notifications

News




  • View Luis Abreu's profile on LinkedIn


    Follow me at Twitter

    My books

    Silverlight 4.0: Curso Completo

    ASP.NET 4.0: Curso Completo

    Portuguese LINQ book cover

    Portuguese ASP.NET 3.5 book cover

    Portuguese ASP.NET AJAX book cover

    Portuguese ASP.NET AJAX book cover