What does ;(function(global,$,_){ }(app,jQuery,_)); mean? [duplicate] - javascript

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.

Related

Limiting the scope of a shared variable (Javascript)

I would like to know if it is possible to have a variable with shared scope between two separate javascript files but not within the root document that references those javascript files.
For example, if I wanted to have a variable that held information about the size of an html element on page load, I could do something like this...
Within the root (index.html) document, I could declare the variable and give it a global scope:
<script>
var elemWidth;
</script>
<script src="first.js"></script>
<script src="second.js"></script>
Within the first javascript file (first.js):
var elem = document.getElementById('myElem');
elemWidth = elem.style.width;
Within an additional javascript file (second.js):
var someDynamicValue = n; /* where 'n' is an integer that is given a calculated value */
if(elemWidth > someDynamicValue) { ... }
Using the above convention, the variable elemWidth is accessible in all three documents (index.html, first.js, second.js). But what if, for whatever reason, I did not want that variable to be accessible in the root document (index.html)? I only want it to be accessible and manipulatable in the two .js files. After all, it's really not needed in the root document (index.html) and I wouldn't necessarily need it in additional .js files (e.g. third.js).
Certain possibilities have come to me, but they all seem to break down at a certain point:
Declaring the variable within one of the two .js files would limit
its scope to that document only. This just doesn't work.
Store the variable as a private property of an object that is declared in the root, and allow that property to be set/get only by the approved .js files
This might be possible by extending the prototype of the ancestor object within the external .js files to include getter/setter methods, but not providing those methods in the document root (which is where the ancestor would have to be declared)
I am not an OOP expert, so this approach might be fundamentally flawed. Feel free to correct me on this!
Consolidate the two javascript files into one, and declare the
variable within that script. This would work, but I may not
necessarily want to or be able to consolidate the separate .js files
in certain circumstances.
Other than that, I am stumped by this question. At this time, I don't have a specific reason to need this functionality, but I can imagine it being useful in certain situations (i.e. additional security, quarantining variable values) and, of course, I am curious and would like to learn something new about JS & OOP through this example.
Perhaps it's just not possible in JavaScript - if so, please explain why :)
Update: I would like to expand on the idea of using object prototypal inheritance to possibly achieve this result. If we declare a class constructor, such as:
function ancestorObj() {
var privateVar = 'secret';
}
And then extend this prototype with another constructor:
function inheritedObj() {
this.getSecret = function() {
return privateVar;
}
}
inheritedObj.prototype = new ancestorObj();
We have now created an object class constructor that is an inherited instance of ancestorObj which contains a getter method that returns the private property of the prototype object. The default class constructor does not contain a getter method. The logic that follows is that only instances of the inheritedObj can get the value of this private property. Can we not then declare instances of inheritedObj only where needed (i.e. 'first.js' and 'second.js'), thereby limiting the scope of the privateVar property?
Again, OOP is not my forte, so this may be easily dismissed as not possible or otherwise incorrect. If so, please explain why.
Ultimately there's nothing you can do to make the symbol completely private to two code units imported from separate <script> blocks. The only relationships such code can have are via global symbols, and if code in two scripts can find your "private" property, any other code can too.
Probably the best thing to do is keep it as a property of some global namespace you claim, or under one you're already using (like a framework).
In your case it'd wrap it into a jQuery method like $.fn.methodName = function { var leaveMeAlone = true; };

Should one re-declare parameters as variables inside a function? [duplicate]

This question already has answers here:
function arguments
(5 answers)
Closed 9 years ago.
Consider:
var success = function(data){
data = process_data(data);
console.log(data);
};
vs.
var success = function(data){
var data = process_data(data);
console.log(data);
};
What are the pros/cons of each?
There is no difference for your ECMAscript interpreter.
Both, formal paramters aswell as local variables are stored in the such called Activation Object (ES3) respectively lexical Environment Record (ES5+).
Those are, special data containers on implementation level which store data belonging to a context, like a function.
While there won't be any differences at runtime, most linting tools will complain about the second piece of code. JSHint gives this error:
'data' is already defined.
If you don't need the original data parameter it's safe to redeclare the variable, but usually it isn't necessary.
On entering function code, the identifiers in the formal parameter list are effectively treated as variable declarations, therefore including them in a var statement inside the function body has no effect.
However, there was an ancient version of Safari that threw an error in cases like:
function (foo) {
foo = foo || {};
...
}
where no value was passed. However, that was a long time ago and certainly not a reason to include var statements for formal parameters.
If you have:
function foo(bar) {
var bar = otherFunc(bar);
...
}
Although this is technically correct, I consider it poor form because you're implying that there are two distinct "bar" variables. That seems like it could cause more confusion later down the line than the version where you don't use "var".
If you want to declare a variable inside then probabley you should declare it with some other name(not similar to the argument).
This way you will be able to reuse the original argument.
If you don't want to use the original argument then you can directly use it. But remember declaring a new variable inside will restrict the scope of the variable.

How are functions scoped/namespaced within a <script> tag?

I'm working with a new application at work that we're building out using Knockout.js and jQuery. I prefer to "use strict" in my scripts, but since some of the libraries we're using don't work with "use strict" then I have to use the functional form.
I don't like placing javascript inside <script> tags inline, so I generally place everything in a separate file so it can be minified and gzipped by a pre-processor.
Given these criteria, I'm wondering how functions are scoped by default when you create them within a script tag. Right now I'm just doing something like this:
$((function(win) {
"use strict";
win.myFunction = function () {
// do stuff
};
}(window)));
As you can see I'm placing functions on my window object so I can call them in my view. I've noticed that I can call them in my jQuery templates without qualifying them (i.e.: I can just call myFunction instead if window.myFunction), but I'm concerned that this will not work across browsers. Do all browsers allow you to call functions placed in the window object without the fully-qualified name? How could I place a function in the global scope from within my anonymous method as I've defined above?
Thanks for the insight!
The window object essentially is the global scope. Any variable that isn't scoped to a function is a property of the window object.
You can set a global variable by setting it as a property of the window object, as you just about do:
window.myFunction = function() {
// do stuff
}
However, it's probably not a good idea to litter your global namespace with names. That way chaos, unmaintainable code and bizarre bugs come in. All jQuery functions, for example, are properties or sub-properties of the jQuery (or $) object. This means that they can define jQuery.each and not have to worry about collisions with a global each method. You should consider doing the same with your own code: create a single global namespacing object to house all your "global" methods.

Enclosing js function between ()? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Difference between (function(){})(); and function(){}();
I have seen it a lot by google:
(function(){/*code*/})
Why they enclose their function inside the parethesis?
Which is the difference between:
function(){/*code*/}
?
Edit
Ok the questions should have been this:
Why they enclose their code into this:
(function(){/*code*/})();
Instead to write the code directly into the js flow?
Are there any benefits, different behaviour?
I usually use immediate functions to control the variable scope so as not to pollute the global name space. It's a very useful pattern.
(function (window, $, undefined) {
// This pattern gives you the following benefits:
// * all variables defined in here are private
// * can safely minify global variables: window, jQuery & undefined
// * ensures that window, $, undefined mean what you expect
// * global variables are localized so lookups are faster
}(this, jQuery));
So even if someone does window = ‘Bob’ or the shortcut $ doesn’t equal jQuery but instead is the Prototype library, the code inside this immediate function will still work correctly. While you may think to yourself “I’d never set undefined to something else”, keep in mind you’re not the only one putting code into the page; you can’t afford to have a poorly written ad script from DoubleClick bringing down the site, especially when it is so easily prevented.
JavaScript’s global scope is like a public toilet. You can’t always avoid it, but try to limit your contact with surfaces.
what you see is a self executing function:
var x = (function(bar){
return bar;
})('foo')
alert(x);
It's usually done to force the parser to treat it as a function expression and not a declaration.
This is because usually the code looks like this:
(function(){/*code*/})();
The reason for the extra parenthesis is that this is not legal syntax:
function(){/*code*/}();
It's needed for immediate functions as #daniellmb said. See explanation of expression closure for more information.

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.

Categories

Resources