This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What do parentheses surrounding a JavaScript object/function/class declaration mean?
I have found the following code in a website .
var testModule = (function(){
var counter = 0;
return {
incrementCounter: function() {
return counter++;
},
resetCounter: function() {
console.log('counter value prior to reset:' + counter);
counter = 0;
}
};
})();
So it follows the syntax var a = (blah balh..)()
What does it actually mean? What is the meaning of variable declaration like a =()()..
It's defining a single-use function and executing it immediately. The code you provided is named the Module Pattern -- see here for more information about its properties: http://www.yuiblog.com/blog/2007/06/12/module-pattern/
A normal function might be created like this:
var f1 = function() {
console.log('bar');
};
And you could subsequently call it like so:
f1();
But in the example you provided, the function is both defined and executed once, and that function returns an object with two functions: incrementCounter and resetCounter. You can call them like so: testModule.incrementCounter() and testModule.resetCounter()
The Module Pattern is useful when you have a single object and you want to encapsulate some properties which are only available to the functions defined in the closure.
The anonymous function is executed and the return value is assigned to the variable.
Related
This question already has an answer here:
Why can’t I assign values to a variable inside a named function expression with the same name?
(1 answer)
Closed 3 years ago.
var functionVariable = function functionExpressionName() {
functionExpressionName = 1;
console.log(functionExpressionName) // function
};
functionVariable();
If You run this example you can see we can not reassign to functionExpressionName anything.
But this is also interesting we can reddeclare functionExpressionName and after this we can assign anything to functionExpressionName
var functionVariable = function functionExpressionName() {
function functionExpressionName() {
}
functionExpressionName = 1;
console.log(functionExpressionName); // 1
};
functionVariable();
If you enable strict mode, the error becomes a bit clearer:
'use strict';
var functionVariable = function functionExpressionName() {
functionExpressionName = 1;
console.log(functionExpressionName) // function
};
functionVariable();
Uncaught TypeError: Assignment to constant variable
The function name is un-reassignable inside the function, but you can create a new variable with the same name inside the function body. One way of looking at it is that the function name is declared with const just outside the function body:
var functionVariable = (() => {
const functionExpressionName = function () {
functionExpressionName = 1; // Clearly wrong - functionExpressionName is a const
// but it would work if you declared a *new* variable,
// which has a different lexical binding
console.log(functionExpressionName) // function
};
return functionExpressionName;
})();
functionVariable();
This isn't exactly what happens, but it's pretty close.
This question already has answers here:
What is the (function() { } )() construct in JavaScript?
(28 answers)
What is the purpose of a self executing function in javascript?
(21 answers)
What is this JavaScript pattern called and why is it used?
(6 answers)
Closed 3 years ago.
I came across this code, which I don't understand what is going on, and then I removed the IIFE parenthesis and the console.log didn't work anymore, can someone explain what is going on,
It is called the classic module pattern.
Why we want to use it?
var foo = (function(){
var publicAPI = {
bar: function(){
publicAPI.baz()
},
baz: function(){
console.log('baz')
}
}
return publicAPI
})()
foo.baz()
foo.bar()
removing the IIFE parenthesis the console.log doesn't work anymore.
var foo = function(){
var publicAPI = {
bar: function(){
publicAPI.baz()
},
baz: function(){
console.log('baz')
}
}
return publicAPI
})
Thank you a lot in advance.
Given:
foo = function () {}
foo is that function.
Given:
foo = function () {}();
foo is the return value of that function.
If you don't call the function, then foo gets a different value.
In the IIFE you are executing the anonymous function inside the first pair of parenthesis (function(){...})() which returns an object having the bar and baz methods inside it.
so after the execution of the IIFE foo refers the publicAPI object, on which you call the bar and baz methods.
If you remove the parenthesis it just becomes a function statement which does not execute the function or returns the publicAPI object. So foo would refer to the function object and until you execute it foo.bar() or foo.baz() won't be available.
//foo is just referring to the function object if you don't execute it
var foo = function(){
var publicAPI = {
bar: function(){
publicAPI.baz()
},
baz: function(){
console.log('baz')
}
}
return publicAPI
}
//Execute foo to get the returned publicAPI object
foo().bar();
foo().baz();
So surrounding a function definition with a parenthesis converts it to an expression and expressions can be invoked.
(function{...}) --> Expression
You can invoke this expression and assign the returned value to variable (in your case it is foo).
var foo = (function{...})() --> Executed the function expression, foo contains the result of the invokation
This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Closed 7 years ago.
I have been writing functions like
var functionname = function(param)
{
}
rather then
functionname(param)
{
}
does it provide any advantage of the format or any garbage collection happens when i write like the first syntax?
(function() { "use strict"; f(); function f() { console.log(1); }; })();
1
(function() { "use strict"; f(); var f = function() { console.log(1); }; })();
Object expected
Function expressions var name = function() { ... } are not hoisted, while function decarations function name() {...} are.
first of all, u should understand the scope matter for this function.
when u write:
var a = function(){} --> the function is anonymous outside the var a- scope.
it means, that out of this district, the function will not be able to be accessed. another thing is memory usage- here u create a function which takes memory, and a pointer outside the function pointing on it as a soft link.
when u write function a(){} ---> there is a public pointer named a for this function as a hard link.
so, if you want to create a private function- go for it.
i know that it's common to create functions using: function funcName(){);
This question already has answers here:
how do I compare 2 functions in javascript
(6 answers)
Closed 6 years ago.
I need to detect whether two anonymous functions are the same.
In the console, why does the following line return false?
(function() { alert("hello"); }) === (function() { alert("hello"); })
Is there a comparison operator or other method to identify that these are 'functionally' the same?
EDIT:
People are asking for the use of this.
It's for removing a function that has been previously pushed into an array of functions. See http://jsfiddle.net/w6s7J/ for a simplified test.
There is no real way to compare 2 different anonymous functions for 'functionality'.
You can check if they are the same object by using your example code.
var func = function () {
alert('hello');
};
alert(func === func);
The above will work, as you are checking to see that both objects are the same.
The only other method for comparing is to compare them as a string.
var func1 = function () {
alert("hello");
};
var func2 = function () {
alert('hello');
};
alert(func1.toString() === func2.toString());
Oops!, they are functionally the same, the difference is the quotes used, So this returns false.
(function() { alert("hello"); }) === (function() { alert("hello"); })
Returns false because they are different objects in javascript.
(function() { alert("hello"); }).toString() === (function() { alert("hello"); }).toString()
Returns true because they are the same strings.
Also function objects have a name property which return the name of the function (but it does not work in IE):
var a = function b() {}
alert(a.name);//write b
This question already has answers here:
How does "this" keyword work within a function?
(7 answers)
Closed 8 years ago.
I have a function in JavaScript:
function main() {
console.log(this);
}
How come this logs Document? Surely it should log function main?
If not, then how do I declare a variable within main to be accessed by the rest of the code as main.varName?
Thank you!
Hey you can do something like this.
But then this would look something like a class object.
<script>
function main() {
this.testVar = "124";
}
var testMain = new main();
alert(testMain.testVar);
</script>
The alternative is that you just create a normal global variable.
The way i am taking the code is a more class object way.
Hope i could help :)
The this keyword references the context of the function, not the function itself.
When you call a function as a method of an object, then this references the object, otherwise the context is the global context (document).
Example:
var o = {
name: 'myObject',
fn: function(){ alert(this.name); }
};
o.fn(); // alerts "myObject"
As a function is also an object, you can add properties to it:
function main() {
}
main.varName = 42;
alert(main.varName); // shows "42"
However, this is not a regular use of functions and objects. Normally main would be a plain object rather than a function if you want to access main.varName.
Also, check out the module pattern
var person = function(){
return module = {
setName: function(name){
module.name=name;
}
}
};
var bill = person();
bill.setName('bill');
console.log(bill.name);