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

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

Related

Scope of a named IIFE name [duplicate]

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).

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.

What does ;(function(global,$,_){ }(app,jQuery,_)); mean? [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.
In one JavaScript file, the script was wrapped into this, why wrap codes into this? Any reference to this? Why define Basepage=global.Basepage?
;(function (global,$,_) {
var Basepage=global.Basepage = Backbone.View.extend({});
}(app,jQuery,_));
By setting a var Basepage, Basepage will become a local variable in that function, and they don't need to write global.Basepage for any further references. Organization like this has several benefits, and I'll try to list each.
Any variables inside the function will be inaccessible to other parts of the code. This is very useful if you declare a common name like var x or var element and don't want it to get mixed up with others as a global variable.
Inside the function, 'app' is referred to as 'global'. Setting 'global.Basepage = Backbone.etc...' means that after that function is executed, app will have BasePage as a property.
Some javascript loader-frameworks depend on this style to be able to initialize a module after all of its dependencies (like JQuery) have loaded.
It is a method of namespacing. With this you get the effect on adding a single variable into the global namespace and you can access it to access other methods and variables.
What it is doing is self executing the function when the code is read, and when it executes, app, jQuery, and _ are passed in as variables to the function, which are what the parameters take on. global = app $ = jQuery _ = _.
This gives you a good way to encapsulate functionality without polluting the global namespace and decreases the risk over overriding variables that have the same name in your application.

how javascript framework have own workspace? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
javascript create INcode workspace (framework)
In the last few days i have been interesting in how Javascript framework have they own workspace , what i mean is how they can call a variable at any name they want and work with it without involving local variables.
I'm writing now an API and i'm facing the problem of the local variables / function local names , if they already exist.
So , what i have done is looking into how framework works and i saw they use namespace functions like this :
(function(){ .... })()
so i tried to do something alike
<html>
<head>
<script type="text/javascript">
(function() {
function f(toAlert) { alert(toAlert); }
})();
</script>
</head>
<body>
<script>
toAlert("hi");
</script>
</body>
</html>
but it's not working..
so i have few questions :
how to have a workspace in javascript to set any variable name i want (if function too it would be great).
i saw that the frameworks uses "window" command , is it have something to do with the namespace function to "public" the function or w/e?
i'll be glad if you can give me information / tutorials about all this thing , how to make it done from beginning to ending
of course it's not working, because your f(toAlert) function is only visible within the immediately executing function closure scope. And you're also trying to call some function that doesn't exists in the first place. Your closure function is called f (and has toAlert parameter), and then you're trying to call function called toAlert that wasn't defined anywhere. Not in global nor in closure scope.
Scope?
This code may clear things up a bit for you. Read comments.
<script type="text/javascript">
// global scope
function globalFunc(text) {
alert(text);
}
var privateFunc = null;
// function closure scope
(function(){
// closure function
function closureFunc(text) {
// can call global
globalFunc(text);
}
// let's make closure function accessible from global scope
// since privateFunc variable is in global scope
privateFunc = closureFunc;
})();
// call closure function
privateFunc("calling closure function");
// ERROR: this will not work due to function being in closure scope
closureFunc("calling closure function");
</script>
Creating local scope
What does that strange function parentheses actually do?
This is some function:
function name(someParameter) { ... }
Putting it in parentheses and adding some at the end, executes it right away:
(function name(someParameter) { ... })("Parameter text value");
Mind the function parameter...
Why do libraries use local scope?
Libraries usually use local scope to not pollute and more importantly clash with other possible libraries. Think of two libraries that would both define a function called getName. The last one that would define it would simply override the first one's implementation thus making the first library to malfunction.
When each library creates its own closure scope they can create whatever functions, variables within and use them without the fear of being overridden. Libraries usually just expose some small part into global scope, so other scripts can actually use the library.
(function() {
var closureVar = "I'm local";
globalVar = "I'm global";
// or
window.globalVar2 = "I'm global equivalent";
})();
omitting var or referencing window object makes a function or variable global.
The script is not working since function f is declared inside another function scope (the outer (function(){..})()) and thus is for local use (inside the same scope) only. That's actually the main point to use this construction, not to clutter global environment with your leftover functions and variables.
There's no toAlert function--that's a parameter to function f. f isn't in scope outside of the immediately-executed anonymous function, however.
If you want to expose f you need to return it from the anonymous function so you can capture and call it.

Will creating a function within a constructor function use more memory than referencing a prototype function? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
JavaScript: Setting methods through prototype object or in constructor, difference?
I guess this is a question about the browsers implementation of closures really. I know about the numerous ways to emulate Class-like functionality within JavaScript including using various libraries. This is more a question about resources.
Does creating a function in this manner create a new copy of public_function function each time it is called? the underlying question is: Does doing it this way use more RAM than adding the function to MyObject.prototype ?
function MyObject(){
this.public_function = function(){
//... do something
}
}
Yes.
If nothing else, this requires a slot on every object created by new MyObject() rather than a single slot on the prototype.
But of course, there is something else: the anonymous function creates a closure, capturing the scope in which it is defined. And again, that has to be stored for every object created by MyObject.
Whether this actually matters will depend on how many objects you create...
See also:
nested function memory usage in javascript
JavaScript instance functions vs. prototype functions
For a class that has mulitipul instances, an anonymous function defined in constructor will create a new copy of function for each instance.
another way without using prototype is that define a static function and assign it to the member. For example:
function A(){
this.hello = Hello;
}
function Hello(){
alert('hello');
}

Categories

Resources