What's the purpose of closures in MVVM modules? [duplicate] - javascript

This question already has answers here:
What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?
(10 answers)
Closed 8 years ago.
I'm working with the following:
define(["knockout"], function(ko) {
var vm = this;
(function() { // I'm tempted to delete this
// init
vm.data = ko.observable("");
// other stuff
})(); // and this
return vm;
});
The person who wrote this said they thought it was a best practice but didn't know why. I understand this is a closure but we don't need any of the "private" functionality that closures provide in this instance, so this just seems like noise to me, but I'm probably overlooking something. What's the point?

You will find a full explanation on that notation in answers to this question: What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?
Short version (sample of accepted answer):
What you're doing when you write (function() { ... code ... })(), is
you're making the code inside a function literal (meaning the whole
"object" is actually a function). After that, you're self-invoking the
function (the final ()). So the major advantage of this as I mentioned
before, is that you can have private methods/functions and properties:
> (function() { var private_var;
>
> function private_function() {
> //code } })()

Related

Why people follow different approach to define function in javascript [duplicate]

This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Closed 8 years ago.
few years back people always define function like this way
1) function foo() {}
now i have noticed people define function like this way
2) var foo= function () {}
3) foo: function() {}
4) var GaugeBar = GaugeBar || {};
GaugeBar.generate = function (percentage) {}
so anyone JavaScript expert would tell me why people follow different approach for defining function? each signature has any special significance ?
when we should follow which one?
looking for good explanation. thanks
I think that there is some confusion in your question - the only valid approach to define a function is 1) and 2). The other two are just different uses of functions in objects.
I personally like to define named functions (function myFunc () {}) because if my program crashes the function names will appear in stack traces. However, there are situations where I use anonymous functions if those functions are not part of a public API or if they are used only once in my program.
Option 3) is basically a function that gets assigned to an object:
var myObject =
{ func: function () {}
, func2: function () {}
}
Option 4) is merely a way how to ensure that a variable contains an object and after that adding some functions to that object.
In practical terms, there is no difference whether you give your functions a name or you use anonymous functions (except for the stack traces and for differences already described in this SO question) and I believe it depends on the programmer's preferred code style. I would love if everyone named their publicly accessible functions as it makes debugging easier, but that's up to each developer to decide.

Javascript difference between store the function into variable with function name or without function name? [duplicate]

This question already has answers here:
Why use named function expressions?
(5 answers)
Closed 8 years ago.
What is the difference between these two functions;
var a = function () { console.log("hi"); }
var b = function xyz() { console.log("hi"); }
When i call these two functions both are giving same result. Then what is point in declaring function name 'xyz' ?
The second form is called a "named function expression". It gives you several benefits over normal function expressions:
It makes it a bit easier to debug -- when you have a bunch of functions like those, and you get an error, naming your functions makes it a bit easier to interpret the resulting stack trace.
You can call named functions recursively -- for example, doing:
f = function f() {
f();
};
f();
...works.
You can find more detailed information here.
Using named function expressions also comes with some disadvantages. For example, doing f = function g() { ... } will actually create two entities -- the functions f and g, which can potentially be confusing. (see comments) There are also some intricacies with scoping which can potentially cause bugs if you're not careful. You can find more detailed information here.

When I should use var function and when function [duplicate]

This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Closed 9 years ago.
I know what the difference between these two are:
var myFunction = function(a) { ... }
function myFunction2(a) { ... }
I just can't figure out when I should use the first one and when the second one.
I saw this var functionName = function() {} vs function functionName() {} but as I said, I know what the difference between these two are.
well, the two options have pros and cons as told in the duplicate post. If you use:
var functionOne = function () { … }
function functionTwo () { … }
then functionOne won't exist in the block prior to its definition, and is being defined at runtime. Whereas the other option, functionTwo is defined at parse time and can be called anywhere in the program. Another thing that changes is the behavior of this inside the function.
So basically, your question is:
how do I want to scope my function?
if scope does not matter, do I prefer run time or parse time?
To get the full answers to those questions, I really advice you to read and reread the short book from Crockford "Javascript the good parts"‎, and it looks like #wumm's suggested article is pretty relevant as well.

Difference between 'var foo = function ...' and 'function foo() ...' [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
“Usual” functions vs function variables in JavaScript
What do you call this JavaScript syntax, so I can research it?
Is there a fundamental difference between
function foo()
{
things();
}
and
var foo = function()
{
things();
}
Or is function ... just syntactical sugar?
Thanks in advance.
They are different (but produce similar results). Basically, the first is an actual named function. The second is a regular variable declaration with an anonymous function attached to it. There are some subtle differences...they are summed up nicely here:
JavaScript Function Declaration Ambiguity (Be sure to read the comments too...more good info there)

What this mean in javascript? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Explain JavaScript's encapsulated anonymous function syntax
I have just read a javascript book but I have seen this code:
1(function() {
// code
})();
what is this ? is a special function ?
As written, it has a syntax error.
I'm guessing it was more like:
(function() {
// code
})();
or
(function() {
// code
}
)();
Break it down:
(FOO)() // calls FOO with no arguments.
And
function() { //creates a function that takes no arguments.
// code
}
Hence together it would create a function that takes no arguments, and then call it. I can't see why you would apart from just showing that you can.
It looks like the intent was to declare the function inline/anonymous and immediately execute it.

Categories