Awkward way of executing JavaScript code [duplicate] - javascript

This question already has answers here:
How do JavaScript closures work?
(86 answers)
Why is this function wrapped in parentheses, followed by parentheses? [duplicate]
(6 answers)
Closed 9 years ago.
In the Google tutorial for implementing Google+ sign-in in Flask application, I discovered that the developer often uses an awkward way of executing JavaScript code:
Instead of doing
var a = foo(bar);
I see this:
var a = (function() {
return foo(bar);
})();
What is the reason to do it the weird way?

This is a poor example. Consider the following:
var a = (function() {
var ret = {};
ret.test = "123";
function imPrivate() { /* ... */ }
ret.public = function() {
imPrivate();
}
return ret;
})();
console.log(a)
a will contain the varible test and the function public, however you can not access imPrivate. This is the common way to handle public vs private variables;
See Why is this function wrapped in parentheses, followed by parentheses? for more info.

var a = (function() {
return foo(bar);
})();
In this case this is really unnecessary, but this is not wrong and it will not throw an error.
But IIF some times uses like module pattern:
var a = (function() {
/* some other code in own scope */
return foo(bar);
})();
In this case IIF is just a module which exports something outside.

The closure function is used to encapsulate some of the attributes / methods in the function. Much like the private / public principle from other languages.
You can find more on this topic here under Module Pattern

Related

Why write a followup set of empty parenthesis when using IIFE? [duplicate]

This question already has answers here:
What is the (function() { } )() construct in JavaScript?
(28 answers)
Closed 7 years ago.
New to JS. Using jonhpapa's Angular style guide and I noticed that when he suggests using the IIFE closure he always adds an extra set of empty parenthesis. Why?
(function() {
'use strict';
angular
.module('app')
.factory('logger', logger);
function logger() { }
})();
To elaborate on my comment - this is an example of a named function:
function x() { console.log('x'); }
In order to invoke the function, you need to add parenthesis after it's name like this:
x();
You do the same thing to unnamed functions in order to invoke them:
(function() { console.log('x'); })();

Javascript: Benefit of naming functions when assigning variables in an object? [duplicate]

This question already has answers here:
Why use named function expressions?
(5 answers)
Closed 8 years ago.
I noticed people in my company like to name functions when assigning it to variables. What are the benefits when it works exactly the same without naming them?
function TargetingForm() {
'use strict';
this.setPristine = function setPristine() {
...
}
//vs
this.setPristine = function() {
...
}
}
In order to ensure the name of the function appears in stack traces when debugging (as opposed to showing up as "anonymous function").
However, many modern javascript engines can derive a useful name for stack traces even when the function is declared anonymously in an assignment expression such as in your second example.
One thing that I can think of (if I am right!) is that you might need to call the function from itself (recursion).
For example you can do this:
function TargetingForm() {
'use strict';
this.setPristine = function setPristine() {
// You can do this
if (someConditionIsTrue) {
setPristine();
}
}
//vs
this.setPristine = function() {
// You can't do the same here!
}
}

Why would I give a function a name, when using the module pattern [duplicate]

This question already has answers here:
Why use named function expressions?
(5 answers)
Closed 8 years ago.
I looked at the jsf.js file of Mojarra 2.2.8 and saw them using the module pattern. Something like this:
name.space = function() {
var utilFunction = function utilFunction() {
// some implementation
};
return {
exposedFunction: function exposedFunction() {
// using utilFunction
}
};
}();
Is there any benefit of giving the functions a name? As opposed to use anonymous functions. They are bound to either a variable or a property of the same name anyway.
Is this some kind of best practice? Does it maybe improve debugging?
I'm just asking, because I usually see the module pattern used with anonymous functions, and was now wondering.
I think it is justified only when using anonymous functions for obvious reading, for example:
async.waterfall[
function makeOne () {},
function makeTwo () {},
];

Why is the function with in parenthesis? [duplicate]

This question already has answers here:
Why is this function wrapped in parentheses, followed by parentheses? [duplicate]
(6 answers)
Closed 8 years ago.
Question:
Why is the function wrapped in a parenthesis? I have taken this code out of parenthesis and it works with no trouble.
What is the benefit of having the code in a (function() { ...Code Here...})(); like it is in the following example?
Code:
(function() {
"use strict";
// Doesn't work because strict mode
// enforces the fact that the second example shouldn't work
if (true) {
function fn1() {
// This won't run
console.log("doesn't work -- have a great Die Hard Day XIII");
};
fn1();
}
})();
Code Here: What would sending the JQuery word as a parameter do for this namespace. I know that the reason that the function is enclosed in (...) is to create a namespace. I guess a better question would be as to why one would pass in a variable, but I would imagine that would be in case another namespace needed the variable.
( function( $ ) {
// Init Skrollr
var s = skrollr.init({
render: function(data) {
//Debugging - Log the current scroll position.
//console.log(data.curTop);
}
});
} )( jQuery );
I have taken this code out of parenthesis and it works with no trouble.
That’s not correct; it can’t run (or even be parsed) by itself. JavaScript sees function in a place where a function declaration can be and assumes it’s a function declaration. Parentheses are used to force the context to be an expression. The practice is redundant if it’s unambiguously a function literal – say, in a variable declaration – but many find it more readable. There’s a jsHint option to enforce it, for example.
Because then they are calling it:
(function() { ... })();
^^

Why CoffeeScript wraps class compiled code [duplicate]

This question already has answers here:
Why does CoffeeScript wrap class definitions in a closure?
(4 answers)
Closed 8 years ago.
CoffeScript compiles this:
class A
a: 'value'
to:
var A;
A = (function() {
function A() {}
A.prototype.a = 'value';
return A;
})();
What is the difference with this:
var A = function A(){};
A.prototype.a = 'value';
I tested the codes in console and the first returns function A(), while the second returns "value", but as a class is intended to be instantiated, to use class A, myA = new A() works for both cases.
There's no effective difference, but since CoffeeScript is a code generator, it likely has other uses for the variable scope in different situations, and is simply not optimized to reduce the code for the simple situations that don't actually need the extra scope.
I don't use CoffeeScript, but that would be my guess.

Categories

Resources