Writing a javascript library
Asked Answered
C

1

8

I want to write a JS library and handle it like this:

var c1 = Module.Class();
c1.init();
var c1 = Module.Class();
c2.init();

And of course, c1 and c2 can not share the same variables. I think I know how to do this with objects, it would be:

var Module = {

     Class = {

         init = function(){
             ...
         }

     }

}

But the problem is I can't have multiple instances of Class if I write in this way. So I'm trying to achieve the same with function, but I don't think I'm doing it right.

(function() {

    var Module;
    window.Module = Module = {};

    function Class( i ) {
        //How can "this" refer to Class instead of Module?
        this.initial = i;
    }

    Class.prototype.execute = function() {
        ...
    }

    //Public
    Module.Class = Class;

})();

I don't have a clue if it's even possible, but I accept suggestions of other way to create this module. I don't know if it's relevant also, but I'm using jQuery inside this library.

Combustor answered 24/9, 2011 at 18:39 Comment(0)
F
14

Usage:

var c1 = Module.Class("c");
var c2 = Module.Class("a");
var n = c1.initial(); // equals 'c'
c1.initial("s");
n = c1.initial(); // equals 's'

Module Code:

(function(window) {
    var Module = window.Module = {};
    var Class = Module.Class = function(initial)
    {
        return new Module.Class.fn.init(initial);
    };
    Class.fn = Class.prototype = {
        init: function(initial) {
            this._initial = initial;
        },
        initial: function(v){
            if (v !== undefined) {
                this._initial = v;
                return this;
            }
            return this._initial;
        }
    };
    Class.fn.init.prototype = Class.fn;
})(window || this);

This is using the JavaScript "Module" Design Pattern; which is the same design pattern used by JavaScript libraries such as jQuery.

Here's a nice tutorial on the "Module" pattern: JavaScript Module Pattern: In-Depth

Friar answered 24/9, 2011 at 18:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.