-1

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?

4
  • Where do you "find" such things? Commented Oct 11, 2013 at 15:02
  • 1
    What do you want to instantiate? MODULENAME is assigned the result of a self-executing function. See stackoverflow.com/questions/592396/… for more details. Commented Oct 11, 2013 at 15:04
  • What exactly do you mean by instantiation? You have essentially created a static class within the var. Commented Oct 11, 2013 at 15:04
  • The javascript module pattern is essentially a singleton (meaning it has only one instance). It has been instantiated. Javscript Module Pattern Commented Oct 11, 2013 at 15:13

3 Answers 3

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().

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.