IIFEs and naming conventions - javascript

Maybe I've missed something specific to angular or javascript that requires this but could someone explain if there's a techical reason CarWashService is defined twice below?
(function() {
angular.module("cw.services")
.factory("CarWashService", ['$sce', '$rootScope', function ($sce, $rootScope) {
var CarWashService;
return new (CarWashService = (function () {
function CarWashService() {
this.results = [];
this.resultsCountText = "";
this.PageIndex = 0;
this.processing = false;
this.initialized = false;
this.showNoResults = false;
this.showResults = false;
this.noCarWashMessage = $sce.trustAsHtml($rootScope.resources.landingNoCarWashMessage);
}
return CarWashService;
})());
}]);
}).call(this);
What could be throwing me off is calling return new on the same line as CarWashService is being assigned. For the javascript gurus out there would it make sense to use a different name other than CarWashService in the IIFE, for readability if nothing else? Or is this an accepted pattern when doing IIFEs?

Whoever wrote that just made it needlessly complex, there is absolutely no benefit from just declaring CarWashService because they aren't making use of the additional closure that they've created. Even if they did need a closure for private state, they have the one from the outer function.
As a side note, this also looks incorrect for angular. If you really wanted a factory, this should probably be returning the constructor rather than an instance of it. This looks like it should be declared as a service.

Related

Proper way for defining services and factories in AngularJS

I read some tutorials for AngularJS and noticed, that everyone is using a slightly different approach how to define a service. I'm wondering whats the best method, or what drawbacks could arise when using a specific approach.
The first difference I noticed, is in using an anonymous function OR a named function:
angular.module('myApp').service('myService', function myService() {
var _var1 = "foo";
var public_methods = {
doSomething: function() {
return "bar";
},
var1: _var1
};
return public_methods;
});
angular.module('myApp').service('myService', function() {
var _var1 = "foo";
var public_methods = {
doSomething: function() {
return "bar";
},
var1: _var1
};
return public_methods;
});
Is there any difference in this two methods?
Does angular provide the myService named function? And how?
The second difference is in defining the "public methods", e.g. what is visible to the outside:
angular.module('myApp').service('myService', function myService() {
var _var1 = "foo";
var public_methods = {
doSomething: function() {
return "bar";
},
var1: _var1
};
return public_methods;
});
angular.module('myApp').service('myService', function myService() {
var _var1 = "foo";
this.doSomething = function() {
return "bar";
};
this.var1 = _var1
});
The first one returns an object, which acts like an interface and defines what is visible to the public. The second one, defines its methods and properties with this.
Are there any drawbacks?
Why would I prefer one method over the other?
The third difference is on defining services like this:
var Session = function() {};
Session.prototype.doSomething = function() {
return "bar";
};
Session.prototype.var1 = "foo";
angular.module('myApp').service('myService', Session);
Here, I only see one drawback, that privat variables cannot be shared with other functions. But does this method has any big advantages? I could imagine that for factories (not services) the performance would be better, because the prototype functions only has to be defined once, and not everytime a new object is created (because a service is a singleton, a factory not).
Defining and using factories: I'm also unsure, if the following method is best practise when using factories:
angular.module('myApp').factory('User', function() {
var User = function(data) {
angular.extend(this, {
id: null,
email: null,
name: null
}, data);
};
return User;
});
And when using the factory, I'm writing new User(data). data gets merged with some default variables etc. What do you think about this method? Is there a big drawback? Or am I using factories in a wrong way?
I think that by and large most of what you're asking - and the reason that you're seeing it done differently - is that these are stylistic differences that are all completely legit JavaScript. There's no real best practices here.
The first question - it makes no difference.
The second question - both work, I have a strong personal preference for the first because it's more flexible; there are nifty tricks you can do that way, object manipulation kind of stuff. You could probably do all of them operating on "this" but it feels unnecessary to me. Again, personal preference.
The third question - this is just a feature of JavaScript which supports first class functions. It's just a language feature and it's going to come down to how you prefer to design things. I inline them but keep each service in its own file. I think that you see people doing it this way because the Angular Documentation on Services shows them doing it that way because it was easier to read in documentation. But it's not much different really.
I don't have a problem with how you're using that factory, but make sure you don't actually want $resource.

How to declare a function: as a separate function or in the same function

Hello Stackoverflow people,
The questions, is about code style and code maintainability, rather than search for some errors.
Let's assume that I am creating some module for node.js. This module, is exporting only one object, let's call this object "FileParser". During file parsing, there can be different preprocessing functions. They are very unique, and I am not planning to reuse them in other parts of the application.
Since, this module is exporting only one function - my question is next:
In case I have some utility functions for this module, should I define this functions in the function which is exported, or they should be defined outside this function.
Basically- this:
var FileParser = function(){
}
FileParser.prototype.methodToExport = function(){
var utilityFunction = function(){
//do some work, maybe even return values
}
//do some other work.
utilityFunction();
//do more other work
}
module.exports.FileParser = FileParser;
or this:
var FileParser = function(){
}
FileParser.prototype.methodToExport = function(){
//do some work before calling function
utilityFunction();
//do more and more work after calling function
}
function utilityFunction(){
//body of function goes here, maybe even returning some value
}
module.exports.FileParser = FileParser;
What is more readable, especially if there are few utility functions.
Thanks,
-D
If utilityFunction is not used as a closure (i.e. it does not access variables declared in the methodToExport function), there is no good reason to declare it inside that other function.
Put it outside, it makes the methodToExport shorter (and therefore more readable).
Since it resides in your "local" module scope, you don't even need to bother about global namespace pollution. If the number of utility functions grows, you might consider grouping them appropriately, e.g. by using the revealing module pattern.
In the first case, your function will be declared each time methodToExport is called, in the second you will have global function. Maybe you can use some kind of closure:
FileParser.prototype.methodToExport = function() {
function utilityFunction () {
//do some work, maybe even return values
}
return function () { // This is the real function, the one which will be export!
//do some other work
utilityFunction () ;
//do more other work
} ;
} () ;
Maybe there is a better way, but I would have done things like that!
JavaScript is flexible enough to permit such thing, the declaration bellow, works but is not a good pratice in my point of view.
var FileParser = function(){
}
FileParser.prototype.methodToExport = function(){
var utilityFunction = function(){
//do some work
}
utilityFunction();
}
module.exports.FileParser = FileParser;
You're declaring and call inside a function, but is more clearly to do this inside the declaration of your FileParser object.
So, you have good pattern of declaration the Revealing Pattern, proposed by Addy Osmani.
var FileParser = function(){
var utilityOne = function(){
}
this.methodToExport = function(){
// do some work
utilityOne();
}
}
module.exports.FileParser = FileParser;
This able you to hide some utility function as a kind of encapsulation, and show only the important functions outside.
You didn't ask about this, but I would recommend that you place your code inside an IIFE so there's one less variable in the top level closure, like this:
module.exports.FileParser = (function(){
var FileParser = function(){};
// Do your stuff
return FileParser;
})();
This saves your having to create a global variable for FileParser.
Now as for the question which you did ask -- should the utility function be defined within the exported function or outside of it -- my answer depends on whether you're only exporting a single function, or multiple. In your case, since you're only exporting a single function, my answer is that as long as you have a choice, I prefer the utility function defined outside because its closure scope is smaller that way. By "as long as you have a choice", I mean that your utility function isn't using anything defined within methodToExport.
module.exports.FileParser = (function(){
var FileParser = function(){};
var utilityOne = function(){};
FileParser.prototype.methodToExport = function(){
// do some work
utilityOne();
}
return FileParser;
})();
A smaller closure scope doesn't make much of a difference in most circumstances, but the following is an example where it does.
module.exports.FileParser = (function(){
var FileParser = function(){};
FileParser.prototype.methodToExport = function(){
var longArray = [ /* ... */ ];
var utilityOne = function(){
setInterval(function(){
console.log("Hello");
},1000);
};
utilityOne();
}
return FileParser;
})();
In the above example, longArray is in the closure of utilityOne() even though it isn't needed. The setTimeout's reference to longArray prevents it from being garbage collected.
module.exports.FileParser = (function(){
var FileParser = function(){};
var utilityOne = function(){
setInterval(function(){
console.log("Hello");
},1000);
};
FileParser.prototype.methodToExport = function(){
var longArray = [ /* ... */ ];
utilityOne();
}
return FileParser;
})();
Moving the utilityOne() definition out of the method definition shrinks its closure scope and allows the longArray to be garbage collected.

Can someone explain the following piece of Javascript code?

I was reading another question, and I saw this:
var basketModule = (function() {
var basket = []; //private
return { //exposed to public
addItem: function(values) {
basket.push(values);
},
getItemCount: function() {
return basket.length;
},
getTotal: function(){
var q = this.getItemCount(),p=0;
while(q--){
p+= basket[q].price;
}
return p;
}
}
}());
Can you please explain why does he wrap the function in ( and )'s? Also, what is the purpose of that return? Couldn't he just write self.addItem = ... and so on?
When you wrap a function with parantheses, and add () to the end of it, it's a self executing function.
(function() x() {
//do something;
})();
And, by returning he's making basket variable somewhat private. Try getting basketModule.basket from anywhere else, and you'll get undefined.
That is called javascript Module Pattern. Defining a function and calling it immediately to prevent variables to be in the global space or to define a function name.
Note parentheses in the last line: (). The function is defined and immediately called:
(function() { })();
return { ... } returns an object having a method addItem
The intention of the code is to create an object with three methods. addItem,getItemCount and getTotal. They all depend on state represented by basket.
if basket was defined globally that state would be exposed (and there could only ever be one variable basket. both of those can lead to issues so by wrapping the entire declaration the state is encapsulated and only accessible from the created object.
There are other ways of achieving the same and the pro's and con's are related to style and how many objects of that particular type you're going to need.
wrapping the function(){}() is required since function(){}() will not parse

Question about functional OOP style in JavaScript

I prefer to use functional OOP style for my code (similar to the module pattern) because it helps me to avoid the "new" keyword and all problems with the scope of "this" keyword in callbacks.
But I've run into a few minor issues with it. I would like to use the following code to create a class.
namespace.myClass = function(){
var self = {},
somePrivateVar1;
// initialization code that would call
// private or public methods
privateMethod();
self.publicMethod(); // sorry, error here
function privateMethod(){}
self.publicMethod = function(){};
return self;
}
The problem is that I can't call public methods from my initialization code, as these functions are not defined yet. The obvious solution would be to create an init method, and call it before "return self" line. But maybe you know a more elegant solution?
Also, how do you usually handle inheritance with this pattern? I use the following code, butI would like to hear your ideas and suggestions.
namespace.myClass2 = function(){
var self = namespace.parentClass(),
somePrivateVar1;
var superMethod = self.someMethod;
self.someMethod = function(){
// example shows how to overwrite parent methods
superMethod();
};
return self;
}
Edit.
For those who asked what are the reasons for choosing this style of OOP, you can look into following questions:
Prototypal vs Functional OOP in JavaScript
Is JavaScript's "new" keyword considered harmful?
You can use Zet.js library which will help you with declaring classes in the way you want.
Several questions occur to me, such as why you want to avoid the new operator, and why you want to call functions before they are defined. However, leaving those aside, how about something more like the following?
namespace.myClass = function(){
var somePrivateVar1;
var self = {};
// initialization code that would call
// private or public methods
privateMethod();
publicMethod();
function privateMethod(){}
function publicMethod(){}
self.publicMethod = publicMethod;
return self;
}
I agree with almost every comment or answer provided so far, but to take Tim's answer one step further - he questioned why you'd want to call a method before it was defined, but offered a solution anyway, whereas I'd suggest you shouldn't call before defining (I don't know of any language where calling a method prior to defining it or at least declaring it is considered good practice), so how about:
namespace.myClass = function(){
//declare private vars (and self) first
var self = {},
somePrivateVar1;
//then declare private methods
function privateMethod(){}
//then public/privileged methods
self.publicMethod = function(){};
// THEN (and only then) add your
// initialization code that would call
// private or public methods
privateMethod();
self.publicMethod(); // no error any more
//then return the new object
return self;
}
Is there a particular reason why this would not work for you?
This is the solution I mentioned in the question. Your comments are welcome.
namespace.myClass = function(){
var self = {},
somePrivateVar1;
function init(){
privateMethod();
self.publicMethod();
}
function privateMethod(){}
self.publicMethod = function(){};
init();
return self;
}

How can I define a function's prototype in JavaScript?

How can I define a function's prototype in JavaScript? I want to do this like I would do it in C where you would do something like:
void myfunction(void);
void myfunction(void){
}
So is there any way to do this in JavaScript? I'm asking this because of the function declaration order that is required in JavaScript.
Edit:
I have an object:
function something(){
var anArrayOfSomethingObjects;
aPrivateFunction(){
// does some stuff
anArrayOfSomethingObjects[3].aPublicFunction();
}
return {
functionA: function() { },
aPublicFunction: function() { },
functionC: function() { }
}
}
privateFunction needs to access publicFunction which is declared afterwards.
How can I do this?
JavaScript is dynamic language there is no need to do that. Meaning Javascript has dynamic binding and dynamic typing, so the check will be on the run time. So no need to define forward declaration like in static languages.
Reply to edit:
Even in this case you still do not need to define forward declaration. Once object will have that method or field in run-time it will work fine. But you probably tackled to the problem of scoping in JavaScript, assuming you asking your question after something gone wrong.
you have to really understand what is a dynamic language, and why your question doesn't really make a lot of sense. your problem is not about 'definition vs. declaration' like on C, it's most about statements order.
in JavaScript (as with most dynamic languages) a function definition like this
function whatever (params) {
...
}
is in fact syntactic sugar for an assignment statement like this:
whatever = function (params) {
...
}
as you can see, whatever is in fact a variable, and it's assigned a function value. so you can't call it before assigning it.
Of course, execution order doesn't have to follow lexical order. If that's your case, you just have to make sure you assign the needed variable before using it. If it's a local variable and you want closure semantics, you can define it first and assign later, like this:
var myfunc = undefined;
function first () {
...
myfunc (...);
...
}
myfunc = function (...) {
...
}
What you are looking for is the Module pattern:
function Something()
{
var someObjects;
var pub = {};
var privateFunction = function()
{
pub.publicFunction();
}
pub.functionA = function() {};
pub.functionB = function() {};
pub.publicFunction = function() {};
return pub;
};
More info and examples: http://www.wait-till-i.com/2007/08/22/again-with-the-module-pattern-reveal-something-to-the-world/

Categories

Resources