Reputation: 3127
I have been working on a JS project and having never worked on a proper JS project before I installed JSHint to keep my JS in line. This lead to me looking at the "use strict" definition which lead to me reading about anonymous functions. Now I'm real confused. I don't know how to properly define my object.
I decided to look at some public js libraries (mainly Bootstrap) on how they do things.
This is the general pattern I see:
(function($) {
'use strict';
var MyObject = function() {
// ...
}
// Prototype methods
})(jQuery);
My questions is how do outside scripts then see the object? I want to be able to pass the object two ids from the initializer.
Upvotes: 1
Views: 66
Reputation: 236
It's an IIFE (immediately invoking function expression).
It purposefully doesn't create global variables. It's used to keep the namespace clean. It's also passing the $ variable (defined as jQuery) as an argument so that it has access to jQuery without pulling in any other libraries that may use the $ sign that the user might be implementing.
I think you may want to look more into the constructor/module/prototypical inheritance patterns, and do some research in to why IIFEs are used (what situations they are good for/bad for).
If you want to use an IIFE and have a function that passes it arguments, or define the argument variables from inside (without polluting the namespace), you can just do it from inside your IIFE.
Off the top of my head example:
(function(){
var Foo = function(arg){
};
Foo.prototype.something = function(){
do something;
};
var Bar = function(){
do something;
return arg;
};
var baz = new Foo(bar());
baz.run();
//or
var ex = something you want to pass as an arg;
var baz = new Foo(ex);
baz.run();
})();
Upvotes: 1
Reputation: 39250
You can export MyObject in the following way
(function(window){
var MyObject = function....
MyObject.prototype. something...
window.MyObject=MyObject;
}(window));
More on constructor functions,prototype and inheritance here:https://stackoverflow.com/a/16063711/1641941
Upvotes: 0