Sunny Jim
Sunny Jim

Reputation: 605

How to define static method classes in javascript

Although I've used Javascript for many years, I'm completely a newbie in terms of all the popular frameworks and libraries. And I have lots of questions about "packages" in that general sense: It would be nice to find a cheatsheet that lists all the general purpose toolkits like JQuery as well as the specialized solutions. But my transition is gradual, and I'm still "rolling my own".

In terms of rolling my own: How can I create classes in Javascript that are not intended to be instantiated in order to bundle static methods? eg:

var mypackage = new Object ;
mypackage.getDocument = function () {
    return document ;
}.bind( mypackage ) ;

mypackage.getCookie = function () {
    return this.getDocument().cookie ;
    }.bind( mypackage ) ;

This example is intentionally trivial, please do not respond with alternatives for retrieving a document cookie.

This example demonstrates my typical approach to define a class or package in Javascript. But I understand that the bind() operator is relatively new and may not be suitable for production. Is that true? Are there alternative approaches?

Upvotes: 0

Views: 355

Answers (1)

Deathspike
Deathspike

Reputation: 8770

I often see them initialized as an object, and do this as well. An example would be:

// Definition.
var mypackage = {
    getDocument: function () {
        return document;
    },

    getCookie: function () {
        return this.getDocument().cookie;
    }
};

// Example.
(function () {
    console.log(mypackage.getCookie());
}());

Upvotes: 3

Related Questions