0

I found a Module pattern in JS:

<script>
var MODULENAME = (function(my, $) {
    my.publicVar = "5";
    my.publicFn = function() {};
    return my;
}(MODULENAME || {}, jQuery));
</script>

However I cannot perform instantiation. Does the module pattern allow for that?

Exegesis
  • 1,028
  • 1
  • 18
  • 47
  • Where do you "find" such things? – Prinzhorn Oct 11 '13 at 15:02
  • 1
    What do you want to instantiate? MODULENAME is assigned the result of a self-executing function. See http://stackoverflow.com/questions/592396/what-is-the-purpose-of-a-self-executing-function-in-javascript for more details. – helpermethod Oct 11 '13 at 15:04
  • What exactly do you mean by `instantiation`? You have essentially created a static class within the var. – Nunners Oct 11 '13 at 15:04
  • The javascript module pattern is essentially a singleton (meaning it has only one instance). It has been instantiated. [Javscript Module Pattern](http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html) – doog abides Oct 11 '13 at 15:13

3 Answers3

3

Instantiantion means basically that you'll run a function using new.

So maybe you're looking for this?

var Some = function (param) {
  var somePrivateVar = 'private';
  this.somePublicVar = 'public';

  this.method = function () {
    return param;
  };
};

var some = new Some('abla');
console.log(some.method());
// some.somePrivateVar === undefined
// some.somePublicVar === 'public'

In your case MODULENAME is an object (object, not a function) with publicVar and publicFn. It's not meant to be instantiated the same way you wouldn't call new jQuery().

kamituel
  • 34,606
  • 6
  • 81
  • 98
1

You can do this also with prototype Inheritance :

var MyClass = function(name)
{
//sharing name within the whole class
this.name = name;
}

MyClass.prototype.getName = function(){
return this.name;//now name is visible to getName method too
}

MyClass.StaticMethod = function()
{
console.log("Im Static");

// and since is not in prototype chain, this.name is not visible
}

    var myclass = new MyClass("Carlos");
    console.log(myclass.getName())//print "Carlos"
MyClass.StaticMethod()// print "Im Static"
myclass.StaticMethod() // error

Se all this article

Misters
  • 1,337
  • 2
  • 16
  • 29
1

Your module object can contain anything. Perhaps you're looking for including a constructor in it:

var MODULENAME = (function(my, $) {

    var privateVar = 10;
    my.SomeConstructor = function() {
        this.publicVar = 5;
    }
    my.SomeConstructor.prototype.someMethod = function() {};
    my.SomeConstructor.prototype.getPrivate = function() { return 10; };

    return my;
}(MODULENAME || {}, jQuery));

var instance = new MODULENAME.SomeConstructor();
instance.publicVar;    // 5
instance.privateVar;   // undefined
instance.getPrivate(); // 10
bfavaretto
  • 71,580
  • 16
  • 111
  • 150