Ok I am definitely learning a lot when it comes to JavaScript scope functions and module patterns, awesome stuff! Right now I’m teaching myself to pass jQuery into a scope function this way it loads sooner, and if for some reason I had another framework that used $, there will be no confusion.
But what I don’t fully understand is when to create a “new” instance “in context to scope functions” when I want to pass in jQuery. Here is what I mean…If I was going to use the following as a base, it will return pubs, which can be associated to a function or properties, etc, I get it.
var DemoA = (function($) {
var pubs = {};
pubs.dosomething = //some function that calculates cool stuff with help of jquery
return pubs;
})(jQuery);
Now when I try to create a new instance….
var stuff = new DemoA();
…I get an error through Google Chrome Developer Tools. It says “object is not a function” or something to that effect. But if I call DemoA directly like this…
DemoA.dosomething();
…then everything works fine. What is going on here? and why can’t I create a new instance variable?
Thanks in advance for helping me get smarter!
Look at your
returnstatement. You’re returning an object that looks like this:You can’t create a new instance of an object. You can call
dosomethingdirectly because it’s an immediate property (method) of the returned object.I think you want something like this:
http://jsfiddle.net/veJqg/
This way, you are still aliasing the
jQueryobject as$, and you are returning afunctionthat can be used in the way you want.