“Static” methods
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.