Writing a javascript library

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

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

And, of course, c1 and c2 cannot use the same variables. I think I know how to do this with objects, this would be:

 var Module = { Class = { init = function(){ ... } } } 

But the problem is that I cannot have multiple instances of the class if I write this way. Therefore, I am trying to achieve the same thing as a function, but I do not think that I am 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 have no clue if this is possible, but I accept suggestions for another way to create this module. I don't know if this matters either, but I use jQuery inside this library.

+8
javascript object module-pattern
source share
1 answer

Using:

 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 is a good module template tutorial: JavaScript module template: depth

+14
source share

All Articles