JavaScript Self Invoking Functions [duplicate] - javascript

This question already has answers here:
Location of parenthesis for auto-executing anonymous JavaScript functions?
(4 answers)
Closed 8 years ago.
Both of these code blocks below alert foo then bar. The only difference is })() and }()).
Code 1:
(function()
{
bar = 'bar';
alert('foo');
})();
alert(bar);
Code 2:
(function()
{
bar = 'bar';
alert('foo');
}());
alert(bar);
So is there any difference, apart from the syntax?

No; they are identical
However, if you add new beforehand and .something afterwards, they will be different.
Code 1
new (function() {
this.prop = 4;
}) ().prop;
This code creates a new instance of this function's class, then gets the prop property of the new instance.
It returns 4.
It's equivalent to
function MyClass() {
this.prop = 4;
}
new MyClass().prop;
Code 2
new ( function() {
return { Class: function() { } };
}() ).Class;
This code calls new on the Class property.
Since the parentheses for the function call are inside the outer set of parentheses, they aren't picked up by the new expression, and instead call the function normally, returning its return value.
The new expression parses up to the .Class and instantiates that. (the parentheses after new are optional)
It's equivalent to
var namespace = { Class: function() { } };
function getNamespace() { return namespace; }
new ( getNamespace() ).Class;
//Or,
new namespace.Class;
Without the parentheses around the call to getNamespace(), this would be parsed as (new getNamespace()).Class — it would call instantiate the getNamespace class and return the Class property of the new instance.

There's no difference - the opening brace only serves as a syntactic hint to tell the parser that what follows is a function expression instead of a function declaration.

There's no difference. Both are function expressions.
There is be a third way, too:
+function() {
bar = 'bar';
alert('foo');
}();
(instead of the + another operator would work, too)
The most common way is
(function() {
// ...
})();
though.

Related

What does placing parenthesis alone around a function mean? (function(){})

I know what an Immediately-Invoked Function Expression is. I know the difference between this
let x = function()
{
}
and this
let x = (function()
{
})()
but what about this
let x = (function()
{
})
do the parenthesis here have any significance alone? I've seen it in several places before.
I thought this was an example but it might not be one X)
edit: Those weren't really intended to be code snippets, anyhow assuming they're snippets, it turns out there's big difference between the case where they are function declarations and function expressions. I didn't expect this. Sorry for the context change and thanks for all the care!
Answer to the edited question:
but what about this
let x = (function()
{
})
There is no purpose served by those () at all. That's exactly the same as:
let x = function()
{
}
Answer to question embedded in comments:
In a comment you've said you actually were wondering about this:
let foo = () => ({ bar: { foo: 1, bar: 2, } });
The () are necessary because that's an arrow function with a concise body returning the result of an object initializer. But if there's a { immediately after the =>, the { would be the opening of a block (verbose) body instead (not the beginning of an object initializer). That's why the () are necessary around the expression body of the concise arrow, to disambiguate the {.
Note that the () are not around the function; just its body.
You can write it the way you did:
let foo = () => ({ bar: { foo: 1, bar: 2, } });
or with {} and return:
let foo = () => { return { bar: { foo: 1, bar: 2, } } };
but not:
let foo = () => { bar: { foo: 1, bar: 2, } }; // Wrong
because the { would be read as the beginning of a block body.
Answer to original question:
I'm going to assume these have names, as otherwise your first example is a syntax error.
but what about this
(function()
{
})
That would be a function expression that isn't immediateley invoked. Unlike your first example, it's evaluated when the step-by-step execution reaches it, instead of when the context it's in is initially created.
Unless something is using the result of that expression, it's a no-op (something that does nothing), since nothing in the expression runs it.
If the result of the expression is being used (it's the right-hand side of an assignment, it's being passed into a function as an argument, etc.), the () around it are unnecessary with a function expression. (That isn't always the case with an arrow function.)
Given the original question:
All else being equal (and it probably isn't because you omitted the context):
This is a syntax error. It starts off as a function declaration and then doesn't meet the syntax requirements.
This is an immediately invoked function expression.
The parenthesis make this a function expression (just like in example 2). It isn't invoked (the () are missing at the end). It isn't assigned anywhere. It does nothing.
But now you've rewritten the question and completely changed the meaning.
Example 3 and Example 1 are now the same.
Putting ( and ) around an expression does nothing except override operator precedence … and there are no operators inside them.
There's no difference between (function() {}) and function() {}.
This lines are also the same :
var test1 = (function() {});
var test2 = function() {};
BUT, if you only write this :
function() {};
You'll get a syntax error. If you don't want a syntax error you have to write this :
(function() {});
But this line is useless and do nothing at all. Because the defined function is never called and no one can access it.
Enclosing a function in parentheses in this way lets you package it for use in another variable or function.
For example, you could use this (somewhat redundantly) to set a variable to a function.
var foo = (function bar() { /* code */ });
foo(); // calls code in bar()
This is also a way to package a callback function, e.g.
asyncFunction((function callback() { /* code */ });
You wouldn't want to use this type of declaration on its own because it becomes hidden to the rest of your code as in the below example.
function foo() { /* code */ };
(function bar() { /* code */ });
foo(); // runs foo code
bar(); // ERROR - bar() undefined in this scope
A similar syntax is used with a trailing parentheses in an "Immediately-Invoked Function Expression". This passes a variable into your function and runs it inline.
(function foo(a) { console.log(a) })("Hello World!");
// Prints "Hello World"
TL;DR - Use it as a way to write a named function inline and package it into another function or variable or, with trailing parentheses, to call your function immediately with a specified input.

When does a function get terminated with }; [duplicate]

This question already has answers here:
Why should I use a semicolon after every function in javascript?
(9 answers)
Closed 7 years ago.
Ok, I asked a question, and someone smarter than me said the question was an "exact" duplicate of mine. Well it wasn't, and the answers did not answer the guy's question. He wanted to know how to call another procedure, I want to know how to call a function within the class. That being said when I was trying to find an answer to my problem and I was looking at answers to similar questions sometimes function were terminated with }; other times with } and still other times with }, (this one I think I understand). However I cannot see in rhyme or reason why or when the brace with a semicolon is to be used and when just the brace should be used:
Here was the first answer
var ExampleClass = function(){
this._m_a = null;
};
ExampleClass.prototype.get_m_a = function(){
return this._m_a;
};
ExampleClass.prototype.set_m_a = function(value){
this._m_a = value;
};
notice this answer doesn't even address the calling of another routine! However the functions are terminated with a }; (Why?)
Here is another answer:
var M_A = function()
{
var m_a; //private variable
this.get = function()
{
return m_a;
}
this.set = function(value)
{
m_a = value;
RunFunction(); //run some global or private function
this.runPublic(); // run a public function
}
}
This guy kinda answers the question but all of the functions are terminated with a } with no semicolon following (Why?)
Finally the answer is unsatisfactory, What is a global or private function? and what is a public function? Why does the public function refer to "this". Anyhow I am probably the village idiot but I still do not know how to call a function I have defined in the class from within the class, and I don't know whether the termination of functions inside a class should be with a }; or just a }. So I have now spent almost 12 hours trying to get one little class to work in javascript to no avail.
Two things are tripping you up.
The first one is the difference between function declarations and function values.
This is a function declaration:
function foo() {
// ...
}
These are function values:
var bar = function() {
// ...
};
var bar = function foo() {
// ...
};
baz(function() {
// ...
});
Function declarations do not need semicolons. Function values are not full statements; full statements do need them (sometimes). It is important to note that in these last three examples, the semicolon does not terminate the function, it terminates the var statement and the function evaluation statement.
This "(sometimes)" is the second point where you have a problem: in JavaScript, a semicolon will be automatically inserted at newline if it is obvious to the interpreter that it should be there.
So,
x = 5
y = 6
is identical to
x = 5;
y = 6;
Thus,
var bar = function() {
// ...
}
is identical to
var bar = function() {
// ...
};
But look at this:
var bar = function() { /* ... */ }; console.log(bar);
is okay (all needed semicolons are there);
function bar() { /* ... */ } console.log(bar);
is also okay, since the function declaration statement does not need a semicolon. However,
var bar = function() { /* ... */ } console.log(bar);
is an error, as the variable assignment statement cannot be separated properly from the function invocation statement. Note that due to automatic semicolon insertion, this works:
var bar = function() { /* ... */ }
console.log(bar);
EDIT: There is a semantic difference between a function declaration statement and assigning a function value to a variable: function declaration statements are executed first (this is called "function hoisting"), while assignments are, as all assignments, executed in order:
function pre_fn() {}
var pre_var = function() {};
pre_fn(); // works
pre_var(); // works
post_fn(); // works
post_var(); // error (not defined yet)
function post_fn() {}
var post_var = function() {};
EDIT2:
I suspect that the class that you were unable to create (as said in comments, code in the question would have been better than speculation) had an object literal form:
var Foo = {
bar: function() {
// ...
},
baz: function() {
// ...
}
};
Here, the semicolon terminates the var Foo = { /* ... */ } statement. You can't have semicolons inside it, for the same reason you can't write
var foo = { a = 6; b = 7 }
because the syntax of the object literal mandates that you separate the key-value pairs with commas. There is no difference here between the numeric value 6, and the function value function() { /* ... */ }; neither "terminates" with a semicolon.

Why are functions assigned to variables in the module pattern? [duplicate]

This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Closed 9 years ago.
In the Module Pattern example from Addy Osmani, a private function is assigned to a variables as shown in this example:
var myNamespace = (function () {
var myPrivateVar, myPrivateMethod;
// A private counter variable
myPrivateVar = 0;
// A private function which logs any arguments
myPrivateMethod = function( foo ) {
console.log( foo );
};
return {
// A public function utilizing privates
myPublicFunction: function( bar ) {
// Increment our private counter
myPrivateVar++;
// Call our private method using bar
myPrivateMethod( bar );
}
};
})();
I would have simply written the private function as:
function myPrivateMethod( foo ) {
console.log( foo );
};
Is there any reason to assign the function to a variable if it's not used as a delegate? I'm looking at some code that uses this pattern consistently and I'm finding it hard to follow. For example:
var _initializeContext = function() { // many lines of code }
This is a function declaration vs a function expression issue. To some degree it's a stylistic choice. What you do need to be aware of is that function declarations get hoisted by the JS interpreter, which function expressions aren't. Some people prefer to use function expressions because they don't like the idea of their code being rearranged.
You might want to check out:
var functionName = function() {} vs function functionName() {}
http://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/
http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html

What is the difference between two declarations of module in javascript?

What is the different between two declarations of a module in JavaScript?
One has parentheses around the function and other one doesn't?
One article says that
Notice the () around the anonymous function. This is required by the
language, since statements that begin with the token function are
always considered to be function declarations. Including () creates a
function expression instead.
Both seem to do the same thing when checked.
var person = (function () {
// Private
var name = "Robert";
return {
getName: function() {
return name;
},
setName: function(newName) {
name = newName;
}
};
}());
var person = function () {
// Private
var name = "Robert";
return {
getName: function() {
return name;
},
setName: function(newName) {
name = newName;
}
};
}();
Functions are of two types in JavaScript - declarations and expressions.
This is the difference between the two:
Function declarations are hoisted. This means you can call the function before it appears in the program as declarations in JavaScript are hoisted.
Function expressions can be invoked immediately. A function declaration cannot. This is because expressions express (or return a value). Function expressions express a function.
An example of a function declaration:
foo("bar");
function foo(bar) {
alert("foo" + bar);
}
The above program will work because foo is a function declaration.
foo("bar"); // throws an error, foo is undefined - not a function
var foo = function (bar) {
alert("foo" + bar);
};
The above program will not work as foo is declared as undefined, hoisted and then later assigned the value of a function expression. Hence it's undefined when it's called.
An example of a function expression:
(function (bar) {
alert("foo" + bar);
}("bar"));
The above function will be immediately invoked as it's a function expression.
function (bar) {
alert("foo" + bar);
}("bar"); // throws an error, can't call undefined
The above function will not be immediately invoked as it's a function declaration. Remember, declarations do not express (or return a value). So it's like trying to invoke undefined as a function.
How does a function become an expression?
If a function is used in the context where an expression is expected then it's treated as an expression. Otherwise it's treated as a declaration.
Expressions are expected when:
You're assigning a value to a variable (i.e. identifier = expression).
Inside parentheses (i.e. ( expression )).
As an operand of an operator (i.e. operator expression).
Hence the following are all function expressions:
var foo = function () {};
(function () {});
~function () {};
Everything else is a function declaration. In short if your function is not preceded by anything, it's a declaration.
See this code: https://github.com/aaditmshah/codemirror-repl/blob/master/scripts/index.js#L94
The following function isExpression is used to test whether some arbitrary JavaScript code is an expression or not:
function isExpression(code) {
if (/^\s*function\s/.test(code)) return false;
try {
Function("return " + code);
return true;
} catch (error) {
return false;
}
}
Hope this clears any doubts in your mind.
In short:
A function expression expresses or returns a value (in this case a function). Hence it can be immediately invoked, but it can't be called before it appears in the program.
A function declaration is hoisted. Hence it can be called before it appears in the program. However since it doesn't express any value it can't be immediately invoked.
In the current context there's no difference for the interpreter. Usually preferable way of writing module is by wrapping the function with parentheses:
var person = (function () {
// Private
var name = "Robert";
return {
getName : function () {
return name;
}
};
}());
That's because the syntax is cleaner and it's obviously that you want to invoke the function immediately after it is declared. One more reason is because:
(function () {
//some stuff
}());
will work but
function () {
//some stuff
}();
this wont.
By wrapping the function each time you use common codding style which is usually a good thing :-).
The difference is that when writing:
var foo = (function () {
...
}());
the use of the (superfluous but useful) grouping () is a common coding style to make it clear from very like first line that the right hand side is most likely an immediately invoked function expression (IIFE). However, in the second:
var foo = function () {
...
}();
it doesn't become apparent until you read the last line, which might be quite a few lines down. Until you reach the last line, you probably thought you were reading a plain assignment:
var foo = function () {
...
};
Note that the parenthesis can be used in a plain assignment too:
var foo = (function () {
...
});
but in that case they really are superfluous (and probably misleading due to the convention of using them for IIFEs).
See An Important Pair of Parens.

Best way to define a function?

I'm always learned to define a function in JavaScript like this:
function myFunction(arg1, arg2) { ... }
However, I was just reading Google's guide to Javascript, it mentioned I should define methods like this:
Foo.prototype.bar = function() { ... };
Question: Is "Foo" in the example an Object, or is it a namespace? Why isn't the Google example the following code (which doesn't work):
prototype.bar = function() { ... };
UPDATE: In case it helps to know, all of my JavaScript will be called by the users browser for my web-application.
Your two examples are not functionally equivalent. The first example simply defines a function (probably a global one, unless you define it inside another function). The second example extends the prototype of a constructor. Think of it as adding a method to the class Foo.
Unless you're building a JavaScript library, my suggestion would be to use neither and use some kind of namespace system. Create a single global object that acts as a namespace through which you can access all your functions.
var MyObject = {
utils: {
someUtil: function() {},
anotherUtil: function() {}
},
animation: {
// A function that animates something?
animate: function(element) {}
}
};
Then:
// Assuming jQuery, but insert whatever library here
$('.someClass').click(function() {
MyObject.animation.animate(this);
});
If you want to emulate classes in JavaScript, you would define the "class" as a function (the function itself being the constructor) and then add methods through the prototype property.
function Foo() {
// This is the constructor--initialize any properties
this.a = 5;
}
// Add methods to the newly defined "class"
Foo.prototype = {
doSomething: function() { /*...*/ },
doSomethingElse: function() { /*...*/ }
};
Then:
var bar = new Foo();
console.log(bar.a); // 5
bar.doSomething();
// etc...
I'm always learned to define a function in JavaScript like this:
function myFunction(arg1, arg2) { ... }
There are two ways to define a function. Either as a function declaration
function foo(...) {
...
}
Or as a function expression
var foo = function() {
...
};
Read more here.
However, I was just reading Google's guide to Javascript, it mentioned I should define methods like this: Foo.prototype.bar = function() { ... };
This is specifically related to method creation for objects, not just normal, stand-alone functions. Assuming you have the base object declaration:
var Foo = function() {
...
};
Just like any other assignment, to assign a function to an object's property, you must use an assignment expression. You can do this two ways. The succinct and common way (as suggested by Google's reference)
Foo.prototype.bar = function() {};
Or, if you want to continue to use the declarative form of defining functions
function bar() {
...
};
Foo.prototype.bar = bar;
This is normally more verbose than necessary, but may be useful in situations where you want to assign the same method to multiple object prototypes.
Question: Is "Foo" in the example an Object, or is it a namespace? Why isn't the Google example the following code (which doesn't work): prototype.bar = function() { ... };
Foo is an object. Although the concept can be expressed through the use of static objects, as I've shown in my answer to your other question, there is no such thing as namespaces in JavaScript. Further, especially in the example code given, Foo is likely intended to be an instantiated object, which precludes it from being behaving like a namespace.
Of course it doesn't work: prototype has not been defined as an object (unless, of course, you define it as such). The prototype property exists on every object (a function is also an object), which is why you can do Foo.prototype.bar = ...;. Read more here.
=====> 2017 Update <=====
This question and answers is 7 years old and is very outdated. This answer includes new syntax for versions of ES5, ES6, and compatible with ES7.
Best way to define a function?
There is no one "Best" way to define a function. How you define the function is dependent on the intended use and lifetime of the function.
Global functions
Defined as a statement with the function token followed by the function name with lowercase camelcase
function functionName (arguments) {
// function body
}
is preferable over the function expression...
var functionName = function (arguments) {
// function body
}
...as the assignment to the variable of the function does not occur until the defining line is executed. Unlike the prefered method which is available immediately after parsing before any code is executed.
const functionName = function(arguments){/*function body*/}
var functionName = function functionName(arguments){/*function body*/}
var functionName = function functionAltName(arguments){/*function body*/}
Function objects
As a function statement with uppercase camelcase function name
function MyObjectFunction (arguments) {
/*function body*/
// if this function is called with the new token
// then it exits with the equivalent return this;
}
const obj = new MyObjectFunction(foo);
Anonymous function expression.
A common practice is to create object via an immediately invoked function that has no name (and is hence anonymous)
;(function (arguments) { /*function body*/ } ("argument val"))
Or
;(function(arguments){ /*function body*/ })("argument val")
NOTE the inclusion of the ; befor the function. This is very important as the open "(" will prevent automatic semicolon insertion on any code above the function.
Immediately invoked function expression.
const functionResult = (function (arguments) {
/*function body*/
return functionResult;
}());
const functionResult = (function (arguments) {
/*function body*/
return functionResult;
})();
As a var or block scopedconst, let
Anonymous callback.
With ES6 you should use the arrow function syntax rather than anonymous function expressions.
myArray.forEach((item,i) => {/*function body*/});
myArray.filter(item => !item);
setTimeout(() => {/*function body*/}, 1000);
Function as properties.
Using the object declaration function shorthand syntax.
var myObj = {
functionName (arguments) {/*function body*/},
}
// called
myObj.functionName("arg");
is preferable over
var myObj = {
functionName : function (arguments) {/*function body*/},
}
Or via function object declarations
function MyObjectFunction(arguments){
this.propertyFunction = function(arguments) { /*function body*/ }
// or arrow notation is fine
this.propertyFunction = (argument) => { /*function body*/ };
}
Functions as prototypes
function MyObj (arguments) {
MyObj.prototype.functionName = function(arguments) { /*function body*/ }
}
or
function MyObj (arguments) {}
MyObj.prototype.functionName = function(arguments) { /*function body*/ }
or
MyObj.prototype = {
functionName(arguments) { /*function body*/ }
}
Defining a prototype function is useful when creating constructors or 'classes' in JavaScript. e.g. a func that you will new
var MyClass = function(){};
MyClass.prototype.doFoo = function(arg){ bar(arg); }
but is of no use in plain old library functions e.g.
function doPopup(message){ /* create popup */};
There are several benefits of using a prototype function including but not limited to
speed
memory usage
extensibility
But, again, this is in the context of creating constructors for instantiable 'classes'
HTH
It works like so:
(function(){ // create an isolated scope
// My Object we created directly
var myObject = {
a: function(x,y) {
console.log('a');
},
b: function(x,y) {
console.log('b');
this.a(x,y);
}
};
})();
(function(){ // create an isolated scope
// Create a Object by using a Class + Constructor
var myClass = function(x,y) {
console.log('myClass: constructor');
this.b(x,y);
};
myClass.prototype = {
a: function(x,y) {
console.log('myClass: a');
},
b: function(x,y) {
console.log('myClass: b');
this.a(x,y);
}
};
// Define a function that should never inherit
myClass.c = function(x,y) {
console.log('myClass: c');
this.a(x,y);
};
// Create Object from Class
var myObject = new myClass();
// Will output:
// myClass: constructor
// myClass: b
// myClass: a
// Define a function that should never inherit
myObject.d = function(x,y) {
console.log('myObject: d');
this.a(x,y);
};
// Test the world is roung
console.log(typeof myClass.c, 'should be undefined...');
console.log(typeof myClass.d, 'should be function...');
})();
(function(){ // create an isolated scope
// If you are using a framework like jQuery, you can obtain inheritance like so
// Create a Object by using a Class + Constructor
var myClass = function(x,y) {
console.log('myClass: constructor');
this.b(x,y);
};
myClass.prototype = {
a: function(x,y) {
console.log('myClass: a');
},
b: function(x,y) {
console.log('myClass: b');
this.a(x,y);
}
};
// Create new Class that inherits
var myOtherClass = function(x,y) {
console.log('myOtherClass: constructor');
this.b(x,y);
};
$.extend(myOtherClass.prototype, myClass.prototype, {
b: function(x,y) {
console.log('myOtherClass: b');
this.a(x,y);
}
});
// Create Object from Class
var myOtherObject = new myOtherClass();
// Will output:
// myOtherClass: constructor
// myOtherClass: b
// myClass: a
})();
(function(){ // create an isolated scope
// Prototypes are useful for extending existing classes for the future
// Such that you can add methods and variables to say the String class
// To obtain more functionality
String.prototype.alert = function(){
alert(this);
};
"Hello, this will be alerted.".alert();
// Will alert:
// Hello, this will be alerted.
})();
Edit: Fixed code so that it will actually run in your browser if you copy and paste :-)
Foo is both an Object and a namespace. See this question.
Using objects as namespaces prevents name collisions. That's always a good idea, but especially when you're developing and/or using shared libraries.
If you don't expect to be making multiple Foo objects (and so don't need the object-oriented style), you could create your functions as methods on a singleton object:
var Foo = {}
Foo.bar = function() { ... }
or
var Foo = {
bar: function() {...},
quux: function() {...}
};
You'd then simply call the function as:
Foo.bar()
(This kind of declaration is roughly equivalent to a static method in C++ or Java.)

Categories