Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript library pattern

I'm trying to figure out the basic pattern for creating a JavaScript library (class). I want to do it in such a way that it doesn't pollute the global namespace with a bunch of junk, but allowing for the class to have instance variables and public methods that modify those instance variables.

Consider the following toy example. I want to make a class Foo. It should contain an instance member, bar, which is a number. There should be a constructor for Foo that takes a number and initializes its instance bar with that number. There should be an instance method that I can call on a Foo object to modify bar. Maybe the code that uses the library looks like this:

var foo1 = new Foo(1);
var foo2 = new Foo(2);
console.log(foo1.bar); // should print "1"
console.log(foo2.bar); // should print "2"
foo2.changeBar(42);
console.log(foo1.bar); // should print "1"
console.log(foo2.bar); // should print "42"

The resultant foo.js would be used by a Web app and therefore included via a script tag in the HTML.

I've done a bit of searching with Google but I have yet to find a single, concise, generic outline of how to design a JavaScript class (used as a library).

like image 924
Shaggy Frog Avatar asked Jul 25 '11 23:07

Shaggy Frog


1 Answers

(function () {
    Foo = function (num) {
         this.changeBar(num);
    };

    var privateMethod = function (x) {
        if (this.bar === 999) {
            this.bar = x;
        }
    };

    Foo.prototype.changeBar = function (num) {
        this.bar = num;
        privateMethod.call(this, 1);
    };

}());

That is the simplest way of doing it. You don't need to include the definition in a closure, more of a style thing.

like image 76
Evan Trimboli Avatar answered Sep 25 '22 14:09

Evan Trimboli