javascript new self invoking function - javascript

I've got a question about self invoking functions in javascript.
What I'm doing is something similar to the following
myNamespace = {}; //namespace for holding any objects/functions
//helpModule as an example
myNamespace.HelpModule = new (function(){
this.abc = '123';
//lots of other code in here...
})();
now I'm able to access properties of myNamespace.HelpModule like so:
alert(myNamespace.HelpModule.abc);
But for starters jsLint doesn't like that saying "Weird construction. Delete 'new'.",
And this page states that you shouldn't use Function Constructor, although in this case I'm not sure if its using the Function Constructor since its a self invoking function?
Anyway, it seems to work fine, and the reason I'm using it is to have "this" scope to the function instead of the global object (window). I could just defining it as an object literal or do something similar to
myNamespace.HelpModule = (function(){
var obj = {};
obj.abc = '123';
return obj;
}();
but neither of these seem as "elegant" to me.
I'm wondering if this is bad form/practice?

It is weird because the purpose of defining a constructor is to be able to reuse it to create many objects.
For your purpose, you can use this construct-
myNamespace.HelpModule = (function(){
//private stuff here
var a = 100;
return {
//public stuff here
b : 200,
something: function() {
return a + this.b;
}
};
})();

Related

The variable that stores the constructor function in JavaScript

My question might be basic but I could not really find a good explanation anywhere. I am new to JavaScript and I am confused about the variable that stores the constructor function and it's functionality, in this example, var MyObject.
The constructor function:
var MyObject = function(){
var self ={
x:250,
y:250
}
return self;
}
The question is, if I do something like below after the above code (outside the constructor function):
MyObject.list = {};
MyObject.connect = function(data){
//do something
};
What exactly is the meaning of this? will it add the new method and the new list to all instances of MyObject?
Is it equivalent to writing the additional list and connect method within the constructor function itself like this:
var MyObject = function(){
var self ={
x:250,
y:250
}
self.list = {};
self.connect = function(data){
//do something
};
return self;
}
What is the equivalent way of achieving this behavior in Java? declaring a static variable/ method?

Passing arguments to a Javascript IIFE constructor

I'm trying to get my head around Javascript OO, using the IIFE module pattern to mimic a class:
var MyClass = (function() {
// Constructor
return function() {
return {
foo: 'foo'
}
}
}());
I'm passing arguments with something like:
var MyClass = (function() {
// Constructor
return function(arg) {
return {
foo: function() {
return 'foo'+arg
}
}
}
}());
To mimic classical inheritance I am using the pattern suggested here:
function inherit(base, child, obj) {
child.prototype = Object.create(base.prototype);
child.prototype.constructor = child;
obj&&Object.keys(obj).forEach(function(key){
child.prototype[key] = obj[key];
})
}
var Base = (function() {
var init = function() {};
init.prototype = {
foo: function() {
return "foo";
}
};
return init;
}());
var Child = (function() {
var init = function() {
Base.call(this);
};
inherit(Base, init, {
bar: function() {
return 'bar';
}
});
return init;
}());
So far so good. My only problem is in understanding how to pass parameters to my class constructor when I'm doing inheritance in the above way. I like the fact that in the 'pure' IIFE module I can simply refer to the constructor parameter in any functions defined within it, so that they become closures. But how do I access constructor params when I'm adding these subsequent functions using the constructor variable, as in the inheritance example above? I suppose I could do something like:
var init = function(arg) {
this.theArg = arg;
};
Then I can access it within anything subsequent:
init.prototype = {
foo: function() {
return "foo"+this.theArg;
}
};
And for the child:
var init = function(arg) {
Base.call(this, arg);
};
This makes arg available to the outside world, so to make it read-only I suppose a getter would work:
var init = function(arg) {
var theArg = arg;
this.getArg = function() { return theArg };
};
On the face of it I can't see anything wrong with that, and I can't think of a better alternative. Is there one? Am I missing something obvious?
I can't think of a better alternative. Is there one?
No. Not in your example.
I like the fact that in the 'pure' IIFE module I can simply refer to the constructor parameter in any functions defined within it, so that they become closures.
You can access args in each function because, in your first example, you are defining foo on each object instance separately. Therefore each definition of foo has a separate closure containing the args passed when it was defined.
This is also only possible, because foo is defined within the scope containing your args.
But how do I access constructor params when I'm adding these subsequent functions ... in the inheritance example above?
By using the classical inheritance patten you found, you are now defining the foo function on the constructor prototype. This means that only a single foo definition exists which is inherited by all instances created using your constructor. So foo can not be made specific to each instance anymore.
As you have figured, it also means foo is no longer defined inside the scope containing args and has no direct access.
You are therefore correct by assigning args to this.thisArgs which allows foo to access thisArgs on each instance. You have made foo a general case function that can handle any instance it is applied to.
Passing arguments to the IIFE constructor: The IIFE itself is not the constructor, it simply builds the constructor object. The IIFE's scope has long since been returned by the time the constructor itself is invoked.
Am I missing something obvious?
Yes. Javascript is a prototypical language. It was never meant to be like "classical" languages. Just let it be Javascript. :)

Where should private methods be placed when using the JavaScript Module pattern?

I've started using the Module pattern in a project of mine. As I understand it, it goes something like this:
var obj = (function(foo){
//Some initialization logic up here.
//Private methods
var privateBazz = function(){
return "I'm known only to this closure!";
}();
//Public methods
return {
publicFoo: foo,
publicBar: function(){
return foo + privateBazz;
}
}
})();
This looked pretty good on paper and, in practice, seems to work reasonably well. Initialization logic at the top is intuitive, then private methods, then public.
I've encountered one issue, though. How should I call publicFoo or publicBar from outside the scope of the return statement and inside the scope of obj's function declaration?
My current solution is to do something like:
var obj = (function(foo){
//Private methods declared early for use.
var privateBazz = function(){
return "I'm known only to this closure!";
}();
var privateBar = function(){
return foo + privateBazz;
};
//Some initialization logic up here.
var dependentOnBar = privateBar();
//Public methods
return {
publicFoo: foo,
publicBar: privateBar
}
})();
This works, but suddenly the declarations of my private variables are placed above my objects private property declarations. The problem becomes exacerbated if I attempt to keep the private function declarations as close to the code which first calls them, so I have just been declaring all the private functions I need at the top, then initializing properties afterwards. Again, this works, but I am used to having code as close to the execution point as possible. So, declaring blocks of private functions at the top is really awkward to me. Does anyone else feel this way, or is this something I just need to get over for JavaScript? Are there any steps I should be taking when I see this happening?
It sounds like you could solve this problem by simply not using object notation to return the module, but rather initialize it and build it as you go. This would go something like this:
var obj = (function(foo){
var self = {};
//Some initialization logic up here.
//Private properties
var foo = "only accessible within this scope";
//Private methods
var privateBazz = function(){
return "I'm known only to this closure!";
}();
//Public Properties
self.publicFoo = foo;
//Public Methods
self.publicBar = function(){
return foo + privateBazz;
};
return self;
})();
here is my solution: if you declare everything before the return as a "private" method and make public those you want to, then you can call your private from within the public and vice versa (in your first sample, your privates can't call the publics as they are not declared at that moment)
var obj = (function() {
// All functions now have direct access to each other
var privateFunc = function() {
return "private "+publicFunc1();
};
var publicFunc1 = function() {
return "public 1 ";
};
var publicFunc2 = function() {
return "public 2 "+publicFunc1();
};
var publicFunc3 = function() {
return "public 3 "+privateFunc();
};
// Return the object that is assigned to Module
return {
publicFunc1: publicFunc1,
publicFunc3: publicFunc3,
publicFunc2: publicFunc2
};
}());
alert(obj.publicFunc3());
If you emulate CommonJS Modules, you can assign properties to the exports object as well as accessing them from elsewhere within the IIFE scope via qualified or unqualified name.
(function (exports, undefined) {
var priv1 = 42;
exports.pubOne = function () {};
var localAlias = function () {};
localAlias(42);
exports.pubTwo = localAlias;
})(window.App);
In this example, Window.App might be my namespaced global object for this module, but you could pass in an empty object or some deeply nested namespace just as easily.

Javascript namespacing - is this particular method good practice?

I'm a javascript newbie, and I've come up with the following scheme for namespacing:
(function() {
var ns = Company.namespace("Company.Site.Module");
ns.MyClass = function() { .... };
ns.MyClass.prototype.coolFunction = function() { ... };
})();
Company.namespace is a function registered by a script which simply creates the chain of objects up to Module.
Outside, in non-global scope:
var my = new Company.Site.Module.MyClass();
I'm particularly asking about the method by which I hide the variable ns from global scope - by a wrapping anonymous function executed immediately. I could just write Company.Site.Module everywhere, but it's not DRY and a little messy compared to storing the ns in a local variable.
What say you? What pitfalls are there with this approach? Is there some other method that is considered more standard?
You dont need to scope classes like that, its only necessary if you have global variables outside of the class. I use this approach...
MyApp.MyClass = function() {
};
MyApp.MyClass.prototype = {
foo: function() {
}
};
Also note that I use a object literal for a cleaner prototype declaration
However if you need to scope global variables then you can do
(function() {
var scopedGlobalVariable = "some value";
MyApp.MyClass = function() {
};
MyApp.MyClass.prototype = function() {
foo: function() {
}
};
})();
Your approach looks fine to me.
However, you can also do this slightly different, by returning the "class" from the self-executing function:
Company.Site.Module.MyClass = (function() {
var MyClass = function() { ... };
MyClass.prototype.foo = function() { ... };
return MyClass;
})();
This strips at least all the ns. prefixes. The namespace function can still be utilized to create the objects, but outside of the self-executing function.

Javascript module pattern, scope and "this"

I'm trying to wrap my head around building a custom JavaScript library. I've read a lot about the module pattern, and also read Crockford's articles on private and public members. I know what is an immediately invoked function expression and why we do stuff like
var myLib = (function() {
}())
However, I'm still a little lost in some cases regarding scope and closures in general. The concrete problem I have is:
Why does the following example alert DOMWindow, rather than the myLib object?
http://jsfiddle.net/slavo/xNJtW/1/
It would be great if you can explain what "this" refers to in all of the methods in that example and why.
Inside any function declared (anywhere) and invoked as follows this will be window object
function anyFunc(){
alert(this); // window object
}
anyFunc();
var anyFunc2 = function(){
alert(this); // window object
}
anyFunc2();
If you want to create private functions and access the instance of 'myObject' you can follow either of the following methods
One
module = (function () {
var privateFunc = function() {
alert(this);
}
var myObject = {
publicMethod: function() {
privateFunc.apply(this); // or privateFunc.call(this);
}
};
return myObject;
}());
module.publicMethod();
Two
module = (function () {
var _this; // proxy variable for instance
var privateFunc = function() {
alert(_this);
}
var myObject = {
publicMethod: function() {
privateFunc();
}
};
_this = myObject;
return myObject;
}());
module.publicMethod();
These are solutions to your issue. I would recommend using prototype based objects.
EDIT:
You can use the first method.
In fact here myObject is in the same scope as privateFunc and you can directly use it inside the function
var privateFunc = function() {
alert(myObject);
}
The real scenario were you can use a proxy for this is shown below. You can use call also.
Module = function () {
var _this; // proxy variable for instance
var privateFunc = function() {
alert(this + "," + _this);
}
this.publicMethod = function() {
privateFunc(); // alerts [object Window],[object Object]
privateFunc.call(this); // alerts [object Object],[object Object]
}
_this = this;
return this;
};
var module = new Module();
module.publicMethod();
You need to explicitly state that myPrivateMethod is a member of myLib:
function MyLib ()
{
this._myPrivateField = "private";
this._myPrivateMEthod = function ()
{
alert(this); // Alerts MyLib function;
}
}
var libObject = new MyLib();
Just remember that without using enclosure techniques, nothing in JavaScript is ever truly private!
A better way to do the above is like so:
function MyLib(instanceName)
{
this.name = instanceName;
}
MyLib.prototype.myPrivateFunction()
{
alert(this);
}
To call your method after that:
var libObject = new MyLib();
libObject.myPrivateMethod(); // Alerts info about libObject.
The thing to remember about the module pattern is that it runs once and completes. The methods that are still available to be called are the closures. At the time of creating module, "this" refered to the window and was replaced by its value.
In your linked fiddle, the "this" keyword is never changed by a "new" keyword or other context change, so it still refers to the global window object.
edit: clarification

Categories

Resources