Just see the code and tell me what kind of Javascript approach is it?
var Arithmetic = function(){
var obj = {
add: function(a,b) { return a + b; },
multiply: function(a,b) { return a * b; }
};
return obj;
}();
var resultAdd = Arithmetic.add(a,b);
var resultMul = Arithmetic.multiply(a,b);
Why people write the js code in this way....any advantage is there for writing such way.
The above code is related to any design pattern? If yes then tell me the name.
I always write the code like this way and it is easy to understand.
function add(a,b)
{
return a+b;
}
function multiply(a,b)
{
return a*b;
}
and i just call it like this way
var x=add(2,3);
var y=multiply(5,8);
also tell me what is the disadvantage of writing code my way.
The disadvantage to writing code your way is that you put lots of stuff in the global namespace. Imagine what happens when you add your code that defines the add and multiply methods that work on numbers and then include a library that deals with Vectors which also defines the add and multiply methods, but which work on vectors. The methods defined last will overwrite the ones previously defined, breaking some of the code that relies on them.
For this reason, it is preferable to not pollute the global scope and when you have functionality you wish to make available, make it available via a namespace (Arithmetic.add() instead of add()).
If you analize the code a bit, var obj is defined not in the global scope, but in the scope of an anonymous function, so code outside of it can use the obj name for a variable without clashing. The functionality (two methods) is exported to public use by returning an object with the two properties from the anonymous function. Since there is no need for more than one instance of the two methods, the anonymous function returns immediately (http://en.wikipedia.org/wiki/Immediately-invoked_function_expression).
Another advantage to this pattern is that it allows to have private variables:
var uniqueId = function() {
var id = 0;
return function() { return id++; }
}();
uniqueId(); // 0
uniqueId(); // 1
In the example above there is no way to accidentally corrupt the uniqueId function to give bad (non-unique) results because you expose just the functional interface you want, instead of the whole mechanism.
Consider the equivalent in your style:
var id = 0;
function uniqueId() { return id++; };
uniqueId(); // 0
id = 0;
uniqueId(); // 0
The code you gave us is an advanced example of Object Oriented code. I don'r really see the advantage of that encapuslated obj right now, that just makes things difficult to read.
Basically Arithmetic acts as a static class. Without that encapsulated obj and the self-executing function, it may be written like that:
var Arithmetic = {
add: function(a,b) { return a + b; },
multiply: function(a,b) { return a * b; }
}
The code you gave us really does the same - it just doesn't write down that object directly but creates it using that self-executing function (that is a closure, a "function without name", that is called (by adding () to it) immediately after it is created).
The advantage of OO code is not really easy to bring down in a few lines, but regarding to static classes as a collection of methods (as it's done here): it's encapusulation.You can treat each class/object you create as a blackbox and don't have to worry about the details (once it works of course).
The disadvantqage of your "traditional" approach is: It get's corweded once you got many, many functions, and you cannot easily tell which "group" they belong to unless you include thst in your naming conventions (like math_add() or math_mul())
Related
I'm reading this page where it says:
myNameSpace = function(){
var current = null;
function init(){...}
function change(){...}
function verify(){...}
return{
init:init,
change:change
}
}();
Instead of returning the properties and methods I just return pointers
to them. This makes it easy to call functions and access variables
from other places without having to go through the myNameSpace name.
But I don't see how that's true. You still have to do myNameSpace.init() to call init. init() alone doesn't work.
Edit: it occurred to me later that maybe the author meant they were able to call init() without qualification inside the anonymous function. But what stumped me is that the author's previous examples were already able to do that. Specifically, in the immediately foregoing example:
myNameSpace = function(){
var current = null;
function verify(){...}
return{
init:function(){...}
change:function(){...}
}
}();
s/he defined init as s/he was returning it, instead of the example above where s/he defined init first then returned a pointer to it. But in that earlier example, within the anonymous function, if you wanted to call init() without having to do myNameSpace.init(), you already can. So how is the quoted example better?.
Can someone explain? Thanks.
The idea of using a function to clean up scope is, let's say you have a program that looks like this:
var number = 10;
var multiplier = 2;
var endingText = " days left!";
var string = (10 * 2) + endingText;
// string is "20 days left!"
This is an extremely contrived example, but hopefully it's obvious enough that this will declare four variables in the global scope, which is horrible. Let's say what you really want is string, but you still want to keep the other three variables around for whatever reason. You can put them inside an anonymous function, like so:
var string;
(function(){
var number = 10;
var multiplier = 2;
var endingText = " days left!";
string = (10 * 2) + endingText;
})();
// string is still "20 days left!"
Because variables are function scoped, number, multiplier and endingText are NOT declared in the global scope. However, you are still able to use them to get the result that you wanted in the first place.
By the way, you need to wrap parens around a function if you want to immediately invoke it. Also, you should not confuse this with namespacing. Namespacing in JavaScript is the idea of assigning meaningful values to the properties of objects.
var foo = {
hello: "goodbye",
frank: "bob"
};
hello and frank are declared in the foo namespace. That's all there is to it. The example that you posted uses both the namespacing concept and immediately invoking function concept to clean up variables.
The wording is a bit confusing. He meant to say:
Functions and variables can now be easily accessed without a namespace from inside the module
- in contrast to the object literal pattern or the previous example where he put the public methods directly on the exported object. Of course, from outside you always will need to access them as properties of the namespace object - that's the whole point of making it a namespace :-)
For an example, let's fill the functions with a some minimal code:
myNameSpace = function(){
var current = null;
function verify(…){…}
return {
init:function(el){
el.addEventListener("input", myNameSpace.change, false);
// ^^^^^^^^^^^^^^^^^^
},
change:function(){
if (!verify(this.value)) alert("wrong");
}
}
}();
myNameSpace.init(document.getElementById("testInput"));
vs
myNameSpace = function(){
var current = null;
function verify(…){…}
function change(){
if (!verify(this.value)) alert("wrong");
}
function init(el){
el.addEventListener("input", change, false);
// ^^^^^^
}
return {
init:init,
change:change
}
}();
myNameSpace.init(document.getElementById("testInput")); // no difference here
The differences may be minimal in this example, but when you have lots of functions mutually referencing each other it can matter. Also, you would know that all local, namespace-less functions belong to the current module, which massively increases maintainability when dealing with many different namespaces.
I'm learning JavaScript at the moment and I don't quite understand when to write a function into a variable.
For instance, both of the following code blocks do the exact same thing in Node.js:
var onReq = function(req, res) {
res.write('Hello');
};
http.createServer(onReq).listen(3000);
and
function onReq(req, res) {
res.write('Hello');
}
http.createServer(onReq).listen(3000);
Which is the best method to do according to best practices, and why?
Usually I'll only use a var funcName = function(){} when I would need to redefine the action(s) for that function later on. For example:
var foo = function(a){ return a * 2; }
var bar = foo(2);
foo = function(a){ return a / 2; }
bar = foo(bar);
Otherwise, for most purposes (assuming it's not a callback or a modifier) declaring a function "classically" is usually acceptable.
I default to the non-variable function onReq(){} version. It's not a concious decision I've made, but thinking about it brings forth these arguments:
It looks cleaner.
It is conceptually simpler: it's just a function, while the other is a function and a variable. It's a small thing, but I find it valuable none the less.
It assures me that onReq will always refer to that function body - one less thing to consider when reading the code. Sort of like marking a variable as final in Java.
Keeps me from "accidentally" replacing the function, causing unintended side effects elsewhere.
I see that nobody mentioned (directly and practically - which seems this question is about) the reason for which I personally find most useful for storing functions in variables. That reason is dealing with a complex logic that requires a lot of choices (e.g. if's) to determine further course of action for which different functions should be called, possibly with different sets of inputs as well. It makes code cleaner when that further course of action is launched in just one place, at the end of our logic.
function fooA (input) {...};
function fooB (input) {...};
let chosenHandler;
let chosenInput;
// Here we establish which function is relevant
if (someCondition) chosenHandler = fooA;
else chosenHandler = fooB;
// Here we establish which parameter should be used
if (someOtherCondition) chosenInput = 'First input';
else chosenInput = 'Second input';
// Call chosen function with chosen parameters - one place, nice and clean
chosenHandler(chosenInput);
If we tried to call functions directly, the code would get much more messy and get the messier the more complex the logic is.
Here is an explaination:
There is a distinction between the function name and the variable the function is assigned to:
The function name cannot be changed, while the variable the function is assigned to can be reassigned.
The function name can be used only within the function's body. Attempting to use it outside the function's body results in an error (or undefined if the function name was previously declared via a var statement).
https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope
According to John Resig's JavaScript as a First Language article, your first code block is considered as best practice.
I personally have encountered certain issues with calling local functions (functions declared inside other functions) when using non-variable syntax in some versions of IE (most likely IE8 or lower) while variable syntax did work as expected.
Given that functions should not be declated in global namespace, most of functions are local, and therefore it makes sense to use variable syntax for functions always.
I see some different opinions here, but most of them are more based on what you think is better or not, but i don't see the technical reasons on when to use one or another, but for sure there are technical restrictions or advantages in use one declaration formula or another. I'm really a beginner with javascript and I don't feel confident to advise on it, but I will propose a case in which storing a function in a variable is not functional.
In the code below, defining an Angular filter, if I define the function inside a variable, then I can't successfully call it from the filter method. Could anyone explain me the technical reason on this?
See the code (commented is not working):
angular
.module('loc8rApp')
.filter('formatDistance', formatDistance);
function formatDistance(){
return function (distance) {
var numDistance, unit;
if (distance && _isNumeric(distance)) {
if (distance > 1) {
numDistance = parseFloat(distance).toFixed(1);
unit = 'km';
} else {
numDistance = parseInt(distance * 1000,10);
unit = 'm';
}
return numDistance + unit;
} else {
return "?";
}
};
};
var _isNumeric = function (n) {
return !isNaN(parseFloat(n)) && isFinite(n);
};
/*
var formatDistance = function () {
return function (distance) {
var numDistance, unit;
if (distance && _isNumeric(distance)) {
if (distance > 1) {
numDistance = parseFloat(distance).toFixed(1);
unit = 'km';
} else {
numDistance = parseInt(distance * 1000,10);
unit = 'm';
}
return numDistance + unit;
} else {
return "?";
}
};
};
*/
Thank you in advance!
I'm building a library (https://github.com/OscarGodson/storageLocker), a localStorage wrapper to be more exact, but because this is my first try at OO JavaScript I'm still learning and I have a couple questions.
I've seen in other libraries that sometimes they wrap them in a anonymous function. Do I, or should I, do that with this? And if so, how without breaking anything?
For the internal API (basically, the internal functions) how should I write them? Should add them to the main object e.g. storageLocker.prototype.myInternalFunction() or just myInternalFunction() randomly in my script? I didn't want the functions to be global though... One of the functions for example just checks a bunch of items in the JSON, sees if their objects, and then checks what the object type is (like Date()) and then converts it.
How/where should I add global, to my script, vars? e.g. i have a var called patterns that is something like var patterns = {"date":/\/Date\(([0-9]+)\)\//} how should I add that into my script?
Thanks a lot. I want to write my script the right way so im asking you guys. I don't know of any JS guys locally that do any OO JS, they're all old school types...
I'd say:
1) the purpose of this technique is not pollute the global namespace. That is a good thing.
In the example below you can see that all your interaction with the library is via one object MyLibrary. Public API is the return value of the anonymous function.
var MyLibrary = function() {
// private
this.InternalVariable = 'some value';
function internalFunction(x,y) {
return x + y;
}
function getInternalVariable() {
return this.InternalVariable;
}
// public
return {
publicVariable : '1.0',
publicFunction : function(x,y) {
return x + y
},
accessInternalVariable : function() {
return getInternalVariable();
}
}
}();
2) see also the example above on how to place your "internal" functions
3) if you global variable is some kind of a configuration option, I'd just make public setter/getter and kept the variable "private"
http://nefariousdesigns.co.uk/archive/2010/10/object-oriented-javascript-follow-up-part-2-technical/
has a decent section on namespacing worth reading.
http://yuiblog.com/blog/2007/06/12/module-pattern/
is also another good overview.
For more great material on good javascript practices, check out
http://javascript.crockford.com/
After our discussion in the comments, I've changed the example to this:
var storageLocker = function (selector) {
var _selector = selector || "default value";
function myPrivateFunction() {
}
var public = {
get: function () {
return _selector;
},
uppercase : function () {
_selector = _selector.toUpperCase()
return this;
}
}
return public;
};
// use:
var test = storageLocker("search for this").uppercase().get();;
alert(test);
While this isn't exactly an example of a library/module (because you're accessing the code by calling the constructor directly), it is an example of keeping the same object in scope for further chaining of methods. Actually it's not returning the storageLocker object, it's returning the 'public' object, but that object has access to the storageLocker's scope through closure.
There could be other better ways to do this by perhaps returning the storageLocker object itself, but that would require a bit more thinking through.
My understanding of closures is that they are essentially a function which uses a variable that you would assume would be out of scope. I guess heres an example I saw the other day:
function closureMaker(somearg)
{
var local_value = 7;
function funcToReturn(arg1, arg2)
{
return local_value + somearg + arg1 + arg2;
}
return funcToReturn;
}
var myClosure = closureMaker(6); //make the closure
myClosure(2, 3); //using it
Now the closure has local_value and even the original arg, somearg. But I dont get why these are helpful. What is the point of using the 'free' variable local_value or even more unknown to me, why would you use the argument of closureMaking function in your closure function?
I'm more interested in how this is used in javascript, Is this used a lot for AJAX requests and objects?
I got the what. I need the why.
One of the most practical and widely spread usage of closures is to implement private or privileged members for example, for example:
function Test (param) {
var secret = 3;
function privateMethod() {
//...
}
this.publicMember = param;
this.privilegedMember = function () {
return secret * param;
};
}
var foo = new Test(10);
foo.privilegedMember(); // 30
foo.secret; // undefined
The module pattern is also a good example that can use the same principle, e.g.:
var myModule = (function () {
var obj = {}, privateVariable = 1;
function privateMethod() {
// ...
}
obj.publicProperty = 1;
obj.publicMethod = function () {
// private members available here...
};
return obj;
}());
A common run-in is that in a for loop, you want to alert the number of the counter.
function addLinks () {
for(var i = 0; i < 5; ++i) {
var link = document.createElement('a');
link.appendChild(document.createTextNode('Link ' + i));
link.i = i;
link.onclick = function() { alert( i ) };
document.body.appendChild(link);
}
}
addLinks();
When you go to click on these links, it will alert 5 because the loop has already been done and i is equal to 5. We didn't "save" the state of i at the time of execution of the for loop.
We can make a closure to "save" that state:
function addLinks () {
for(var i = 0; i < 5; ++i) {
var link = document.createElement('a');
link.appendChild(document.createTextNode('Link ' + i));
link.i = i;
link.onclick = (function(i) { return function() { alert(i ) } })(i);
document.body.appendChild(link);
}
}
addLinks();
The i is bound to the self executing anonymous functions invoked within each increment in our loop. This way the state is saved and we get the right # on alert.
The example you're looking at is trying to show you how closures work. I think of closures as little pieces of code that you can pass around. The neat thing is that (free) variables in the closure are bound based on the current lexical scope. This is why local_value keeps the value 7 because that's what the value of local_value was when the closure was created.
Javascript implements closures via anonymous functions*, but keep in mind that technically, these are two separate concepts.
In the context of Javascript, closures (implemented as anonymous functions) are very helpful when you want to deal with things that happen asynchronously; a good example is, like you stated, AJAX requests where you cannot predict when you will get a response back from a server. In this case, you have an anonymous function called a callback that you initially define and pass in when you make the AJAX call. When the call successfully completes, your callback is called to process the result. Closures result in cleaner code since you can package behavior and logic inside them. It also helps you abstract the behavior our and separate concerns.
Another use for anonymous functions/closures is for event handling. When an event happens your event handler is called.
Like I had mentioned before, you can abstract behavior and logic and put it in a closure. But what really makes a closure so powerful is context. You can customize the behavior of your closure, depending on the environment in which it was created. This makes your function very versatile, because you are defining its arguments (which will influence its behavior) while you are creating it, instead of when you are calling it (with explicit parameters) during execution.
Here is a good article about closures in Javascript. It's long, but informative:
Javascript Closures
* As CMS mentioned, named functions will behave like anonymous functions because they will have access to variables that are defined in the same lexical scope (or anything up the chain). This is most evident in inner functions. But if you think about it, the same happens for any function; you have access to variables that have been defined in the global scope (i.e., global variables).
This is probably not quite what you are looking for but there is an excellent talk about closures for Java (how they should/could be implemented) that also goes into some examples on where you would want to use them
http://www.youtube.com/watch?v=0zVizaCOhME
Closures are an easy way to make functions that depend on parameters. Or to put it another way, to create a specific instance of a family of functions (read on if that's not clear) depending on some run-time value.
Javascript lets you pass functions around as first-class members; so for example, you could pass around a function that determines how to combine two integers by referring to it directly.
However, going one step further, a closure lets you create a "customised" version of a function, whose exact behaviour depends on some runtime variable (but which otherwise conforms to a framework).
For example, here's a function that will allow a curried addition:
function getAddNFunction(n)
{
function inner(operand)
{
return n + operand;
}
return inner;
}
Now if you call getAddNFunction(7), you get a function that adds 7 to an argument. If you call getAddNFunction(42.5), you get a function that adds 42.5 to the argument.
Hopefully this simple example clarifies the benefit of closures; they allow you to embed arguments in the function at creation time rather than them having to be passed in at execution time (after all, calling getAddNFunction(9)(2) is exactly the same as calling 9 + 2, except for the fact that the two arguments can be supplied at very different times).
So for instance you might want to return some kind of complex XML parsing function relative to some root element; a closure lets you embed that root element definition within the function itself, rather than depend on the caller having access to it whenever they want to execute the function.
If you are comnig from an OO world, closures allow you to create what are essentially private member variables, and methods, for your objects:
function Constructor(...) {
var privateVar = value;
function privateFunc() {
}
this.publicFunc = function() {
// public func has access to privateVar and privateFunc, but code outside Constructor does not
}
}
Douglas Crockford and javascript goodness
In addition to above closure helps in hiding some of the implementation detail.
var Counter = (function() {
var privateCounter = 0;
function changeBy(val) {
privateCounter += val;
}
return {
increment: function() {
changeBy(1);
},
decrement: function() {
changeBy(-1);
},
value: function() {
return privateCounter;
}
}
})();
alert(Counter.value()); /* Alerts 0 */
Counter.increment();
Counter.increment();
alert(Counter.value()); /* Alerts 2 */
Counter.decrement();
alert(Counter.value()); /* Alerts 1 */
One more good article
Read this article on module pattern in javascript which heavily uses closures.
I've heard from a variety of places that global variables are inherently nasty and evil, but when doing some non-object oriented Javascript, I can't see how to avoid them. Say I have a function which generates a number using a complex algorithm using random numbers and stuff, but I need to keep using that particular number in some other function which is a callback or something and so can't be part of the same function.
If the originally generated number is a local variable, it won't be accessible from, there. If the functions were object methods, I could make the number a property but they're not and it seems somewhat overcomplicated to change the whole program structure to do this. Is a global variable really so bad?
I think your best bet here may be to define a single global-scoped variable, and dumping your variables there:
var MyApp = {}; // Globally scoped object
function foo(){
MyApp.color = 'green';
}
function bar(){
alert(MyApp.color); // Alerts 'green'
}
No one should yell at you for doing something like the above.
To make a variable calculated in function A visible in function B, you have three choices:
make it a global,
make it an object property, or
pass it as a parameter when calling B from A.
If your program is fairly small then globals are not so bad. Otherwise I would consider using the third method:
function A()
{
var rand_num = calculate_random_number();
B(rand_num);
}
function B(r)
{
use_rand_num(r);
}
Consider using namespaces:
(function() {
var local_var = 'foo';
global_var = 'bar'; // this.global_var and window.global_var also work
function local_function() {}
global_function = function() {};
})();
Both local_function and global_function have access to all local and global variables.
Edit: Another common pattern:
var ns = (function() {
// local stuff
function foo() {}
function bar() {}
function baz() {} // this one stays invisible
// stuff visible in namespace object
return {
foo : foo,
bar : bar
};
})();
The returned properties can now be accessed via the namespace object, e.g. ns.foo, while still retaining access to local definitions.
What you're looking for is technically known as currying.
function getMyCallback(randomValue)
{
return function(otherParam)
{
return randomValue * otherParam //or whatever it is you are doing.
}
}
var myCallback = getMyCallBack(getRand())
alert(myCallBack(1));
alert(myCallBack(2));
The above isn't exactly a curried function but it achieves the result of maintaining an existing value without adding variables to the global namespace or requiring some other object repository for it.
I found this to be extremely helpful in relation to the original question:
Return the value you wish to use in functionOne, then call functionOne within functionTwo, then place the result into a fresh var and reference this new var within functionTwo. This should enable you to use the var declared in functionOne, within functionTwo.
function functionOne() {
var variableThree = 3;
return variableThree;
}
function functionTwo() {
var variableOne = 1;
var var3 = functionOne();
var result = var3 - variableOne;
console.log(variableOne);
console.log(var3);
console.log('functional result: ' + result);
}
functionTwo();
If another function needs to use a variable you pass it to the function as an argument.
Also global variables are not inherently nasty and evil. As long as they are used properly there is no problem with them.
If there's a chance that you will reuse this code, then I would probably make the effort to go with an object-oriented perspective. Using the global namespace can be dangerous -- you run the risk of hard to find bugs due to variable names that get reused. Typically I start by using an object-oriented approach for anything more than a simple callback so that I don't have to do the re-write thing. Any time that you have a group of related functions in javascript, I think, it's a candidate for an object-oriented approach.
Another approach is one that I picked up from a Douglas Crockford forum post(http://bytes.com/topic/javascript/answers/512361-array-objects). Here it is...
Douglas Crockford wrote:
Jul 15 '06
"If you want to retrieve objects by id, then you should use an object, not an
array. Since functions are also objects, you could store the members in the
function itself."
function objFacility(id, name, adr, city, state, zip) {
return objFacility[id] = {
id: id,
name: name,
adr: adr,
city: city,
state: state,
zip: zip
}
}
objFacility('wlevine', 'Levine', '23 Skid Row', 'Springfield', 'Il', 10010);
"The object can be obtained with"
objFacility.wlevine
The objects properties are now accessable from within any other function.
I don't know specifics of your issue, but if the function needs the value then it can be a parameter passed through the call.
Globals are considered bad because globals state and multiple modifiers can create hard to follow code and strange errors. To many actors fiddling with something can create chaos.
You can completely control the execution of javascript functions (and pass variables between them) using custom jQuery events....I was told that this wasn't possible all over these forums, but I got something working that does exactly that (even using an ajax call).
Here's the answer (IMPORTANT: it's not the checked answer but rather the answer by me "Emile"):
How to get a variable returned across multiple functions - Javascript/jQuery