Scope of a named IIFE name [duplicate] - javascript

This question already has answers here:
Why does a named IIFE result in a ReferenceError outiside of it?
(2 answers)
Closed 6 years ago.
I thought I understood the nature of Immediately Invoked Function Expressions (IIFEs), but now I realise I don't.
I created an IIFE in a piece of code (in a web page using JQuery as it happens). However if I name the function, and try to call that function from the enclosing scope I get an "undefined" error?
The live code behaves differently in IE11 and Firefox 38, which makes things even more confusing. However I created a simple test JSfiddle here-
https://jsfiddle.net/ktqq4uat/
and this is consistent between browsers.
I thought these two lines-
(function myFunction2() {
...
(myFunction3= function() {
...
were pretty much equivalent, but I get an undefined error on "myFunction2" only.
I'd appreciate some help understanding-
1) Why (function myFunction2() {... is hiding the name of the function as well as it's internal scope. What IS the scope of that name?
2) Why myFunction2 and myFunction3 above behave differently.
Rgds

Named function expressions only create a variable that:
has the same name as the function
has a value that is a reference to that function
in their own scope. They also evaluate as a reference to that function so you can pass that reference somewhere (e.g. assign it to myFunction3).
Function declarations create a variable like that in their parent scope. They don't evaluate as anything (because they aren't expressions).

Related

Why is .call(this) used instead of parenthesis [duplicate]

This question already has answers here:
Reason behind this self invoking anonymous function variant
(5 answers)
Closed 8 years ago.
Is there a particular reason why i often encounter:
(function() {
console.log("Hello");
}).call(this);
instead of:
(function() {
console.log("Hello");
})();
It should have the same effect when passing this to call or not?
There seems to be some performance difference: http://jsperf.com/call-vs-parenthesis.
Presumably the code within that function uses this (where you just have console.log). In the version with call, this within the function is the same as this outside it. Without call, this inside the function is either the global object (loose mode) or undefined (strict mode).
If you're not using this within the function, there's no reason to be doing the call version, and I would lean toward not doing so because it's additional unnecessary complexity (and apparently a very very small performance cost).
The addition of .call(this) is important, it changes the context of the function enclosure, meaning that the this keyword will refer to the same this as the outer function enclosure.
In your particular code it doesn't make any difference because inside your function you do not refer to this at all.
this.a = 123;
(function() {
console.log(this.a); // always 123 regardless of scope
}).call(this);
That is significant assuming that this refers to something other than the window object. If this is already pointing to the window, then adding .call(this) makes no difference, since without it, by default the this will go to the window.

Strange use of function within brackets [duplicate]

This question already has answers here:
How does the (function() {})() construct work and why do people use it?
(15 answers)
Closed 9 years ago.
Can someone explain to me what below code does, how it works and why it is used?
I don't understand why the function is within brackets or the brackets after the curly brackets.
(function () {
//Some javascript code...
}());
Thank you.
Edit/Follow up question:
Now that I better understand what above does, what effect would this have when used with jQuery:
$(document).ready(function () {
(function () {
//code here
}());
});
That is a self-executing function. It creates an anonymous function and immediately executes it.
It can be used for many purposes, such as creating a new scope.
var x = 10
(function () {
var x = 5
}())
alert(x) // 10
This is a self executing anonymous function.
First is the anonymous function:
(function(){
//Normal code goes here
})
The really interesting part is what happens when we add this right at the end:
();
Those brackets cause everything contained in the preceding parentheses to be executed immediately.
Javascript has function level scoping. All variables and functions defined within the anonymous function aren't available to the code outside of it, effectively using closure to seal itself from the outside world.
This design pattern is useful for modular Javascript.
You may read more here:
What is the purpose of a self executing function in javascript?
#doornob is correct. However, there is a syntax error in the original post. It should look like this:
(function() {
// your code goes here
})();
While this is commonly described as a "self-executing function", a more accurate term is "Immediately Invoked Function Expression." We can call that an "iffy." This is a type of closure.
This pattern is is commonly extended into something called the module pattern, which looks like this:
var myModule = (function() {
var my = {};
var privateFoo = 'I am foo. I am a private field!';
my.publicMethodGetFoo = function() {
return privateFoo;
}
return my;
}) ();
This is very much like a class in a traditional OOP language such as C++ or Java. The properties declared using the var keyword cannot be accessed outside of the module. Though there is no such thing as access modifiers in JavaScript, these properties are for all intents and purposes 'private'.
Note that we created an object called 'my'. This object is returned at the end of the module, which means it is exposed to the 'outside world.' Therefore it's accessible outside of the module. Any field or method that we add to 'my' will therefore be public.

Javascript weird way of declaring and calling a function [duplicate]

This question already has answers here:
What is the purpose of a self executing function in javascript?
(21 answers)
Closed 9 years ago.
Hi I am new to javascript and I am trying to maintain someones code, but I cant seem to figure out what they are doing.
They seem to be declaring a function like so:
(function(Module) {
Module.register(...) {
....
return ...;
};
Module.register(...) {
....
return ...;
};
}(hb.Core));
If you wanted to create a function that called Module.register twice (which is what I think they are trying to do), wouldn't you do the following?
function myFunction(Module) {
Module.register(...) {
...
};
Module.register(...) {
...
};
}
myfunction(Module);
Also, don't know if this is really relevant, but they are using the sandbox model (where they have different modules communicate with the application core only through a sandbox).
Hope someone can help out. I am really new to Javascript and front-end development in general and I am very confused.
Duplicate What is the purpose of a self executing function in javascript?
it's a self executing anonymous function call. your example is a function declaration where you've assigned the function a name so it is no longer anonymous. self executing functions are used when there is a need to scope your variables to only be available to anything in side the self executing function.
If you mean that function
(function(Module) {}(hb.Core));
It is a self invoking function receiving hb.Core value for its Module parameter.
In javascript functions declare scopes so this is the primary reason for the one above.
The variable inside that function are not accessible outside of it , which means outside of it's scope

How do jQuery's namespaces work? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
What does this JavaScript/jQuery syntax mean?
I specifically mean when you do this:
(function ($) {
...
})(jQuery);
I've never seen that kind of syntax before. How does the function get called? I understand when you do it like this:
jQuery(function ($) {
...
});
because the function is being passed to jQuery, and jQuery can just run any function passed as a parameter when the DOM's ready, but the first one's different.
Duplicate of What does this JavaScript/jQuery syntax mean?
I'll post my answer here, though seeing as Jeff Attwood seems to want us to embrace duplication: (https://blog.stackoverflow.com/2010/11/dr-strangedupe-or-how-i-learned-to-stop-worrying-and-love-duplication/)
This convention is used when writing plugins to ensure there is no confilict with other Javascript libraries using the $ notation, whilst ensuring the plugin author can still use this notataion:
(function($){
...
})(jQuery);
The author is declaring an anonymous function with a single parameter ($), then immediately calling it and passing the jQuery object to it. This ensures the function is called and that everything in it is defined.
A longer notation might be:
function MyDefs($){
...
}
MyDefs(jQuery);
Although that would create a variable MyDefs in the global namespace. The anonymous function pattern leaves the global namespace empty, avoiding conflicts.
It's an anonymous function. When you write:
(function ($){
..
})(jQuery);
It is mostly equivalent to:
function the_function($) {
..
}
the_function(jQuery);
The only difference being that the first does not create a function called the_function and therefore created no risk of accidentally overwriting an existing function or variable with that name. And of course, all of it is equivalent to:
function the_function() {
var $ = jQuery;
..
}
the_function();
The point of this construct is that any variables defined inside the_function are local and therefore cannot accidentally overwrite any variables or functions in the global scope. For instance, the code inside the function uses $ to represent the jQuery object, but this would conflict with other libraries that use $ as well (such as Prototype). By wrapping the usage of $ inside a function, the Prototype code outside the function remains unaffected.

Does parenthetical notation for self-invoked functions serve a purpose in Javascript? [duplicate]

This question already has answers here:
Explain the encapsulated anonymous function syntax
(10 answers)
Closed 8 years ago.
I get confused when I see examples of self invoked anonymous functions in Javascript such as this:
(function () { return val;}) ();
Is there a difference between this syntax and the following:
function() { return val;} ();
If someone can give me a concrete difference, it would help put to rest a question that's been bugging me for ages...
Javascript doesn't have a block scope, so this is a way to create a temporary local scope that doesn't pollute the global namespace. The parentheses serve two purposes:
Some implementations of javascript flip out if they're missing.
It signals to readers that something different from a normal function declaration is going on. So as a convention, it signals that this function is being used as a scope.
see here:
http://peter.michaux.ca/articles/an-important-pair-of-parens
In Safari 4, the following code (without the parentheses) results in "SyntaxError: Parse error":
function() { alert("Test"); }();
...but the following code works as expected:
(function() { alert("Test"); })();
Update: I also tried the code in Firefox 3 (via Firebug), and it behaved just like Safari.
The reason
function() { return val;} ();
doesn't work is because it's a function statement, not an expression. It's a pretty minor distinction, but basically, if the statement starts with function, it's just like a C function declaration, and you can't call the function, because there is no expression value.
Adding the parentheses makes the function definition part of an expression, so it has a value and can be called.
Assigning the return value of the function also eliminates the need for parentheses, because the function definition is not the whole statement. For example, these work:
var value = function() { alert("works"); return 0; }();
(function() { alert("works"); })();
but this doesn't:
function() { alert("doesn't work"); }();
I always include the parentheses, even when they aren't necessary because it makes it easier to see that I'm calling the function, instead of assigning it to a variable.
As far as I know, the only difference is that the latter sometimes doesn't work in certain flavors of ECMAScript (namely ActionScript, but there could be others).

Categories

Resources