I am using jQuery in some custom files added to a Wordpress site, and am using this to allow me to use the "$" shortcut:
jQuery(function ($) {
$(selector).bla();
// etc
}
However, if I want to split my code into several files, this construct needs to exist in each file, and then functions from one cannot be called from the other. How to do this? Can I somehow declare certain functions as global?
You might want to look at using requirejs to define modules, then pass the modules in as dependencies. You can also use it to define jQuery as as dependency so that it can be scoped locally with whatever variable name you want.
require(['jquery','somemodule','someothermodule'], function($,module1,module2) {
$(function() {
var mod1 = new module1();
var mod2 = new module2();
...
});
});
You can use something like this:
var myFunc = function($) {
function toExport() {
alert($);
}
return toExport;
}(jQuery);
Just return resources you need (it can be single function, or object, or anything you want actually.)
jQueryUI is actually written a similar way:
(function( $, undefined ) {
...
}( jQuery ) );
This way the $ is guaranteed to be a synonym for the jQuery function and the keyword undefined will be defined as parameter with an undefined value. The undefined portion actually fixes some nit picky issues with a few browsers since they don't all handle undefined the same way.
You can always declare functions outside the jQuery(function() {...}); construct, in global scope.
You just cannot access the DOM before it is ready, which means you cannot execute those functions outside jQuery(function() {...}); if they access the DOM.
You can also always create a global variable by assigning a value to window property:
window.theanswer = 42;
Adding many values to the global namespace is not a good practice, and other techniques exist to create modular JavaScript to solve this problem. See tvanfosson's answer.
Related
The closure wrapper (function($){..})(jQuery); is a great way to have local variables instead of global ones. Both $ and any variable and local function defined within the wrapper is visible only within the wrapper, not outside. This is great, and I use it all the time.
(function($){
[..]
})(jQuery);
However, I have been wondering why we pass jQuery (and possibly other stuff) as an argument, instead of using a local variable declaration.
(function(){
var $ = jQuery;
[..]
})();
Wouldn't this work just as fine, and be more transparent?
I see one reason when former way is better:
(function(){
var $ = jQuery;
[..]
var jQuery = foo;
})();
In this example variable "$" will be undefined because of hoisting.
There's an advantage in terms of code length. It saves a few characters (bytes...). It's not much, but if you have to choose between the 2, the first example is shorter.
In the sake of minification, it's also possible (and to some degree common) to use an "unset" variable to serve as an undefined match like this:
(function(r,u){if(r.missingProp===u)alert('undefined!')})({realProp:1})
Since u isn't passed a value during the call, it will equal undefined
This question already has answers here:
What does !function ($) { $(function(){ }) }(window.jQuery) do?
(1 answer)
Why write code Jquery like this
(4 answers)
Closed 9 years ago.
I am a javascript newbie and recently came into the following code.
(function($){
if(!document.defaultView || !document.defaultView.getComputedStyle){
var oldCurCSS = jQuery.curCSS;
jQuery.curCSS = function(elem, name, force){
if(name !== 'backgroundPosition' || !elem.currentStyle || elem.currentStyle[ name ]){
return oldCurCSS.apply(this, arguments);
}
var style = elem.style;
if ( !force && style && style[ name ] ){
return style[ name ];
}
return oldCurCSS(elem, 'backgroundPositionX', force) +' '+ oldCurCSS(elem, 'backgroundPositionY', force);
};
}
})(jQuery);
What is function($) {...} (jQuery)?
PS: I also don't quite get what the code is for... If possible please give a hint on it.
It's a self-executing anonoymous function called with jQuery as argument, that gets renamed to $ inside the function signature.
Since you don't know if jQuery.noConflict() has been used in the page (especially if you are writing distributable code like Plugins), this way you can use the shorthand $ inside your function safely.
Who wrote it is actually stupid beacuse he's using jQuery inside the function anyway : )
It also prevents the variables from polluting the global namespace and encapsulates them making them unaccessible from outside the function.
That's to prevent the code from interfering with a global variable named $, so that you can use other libraries that use the $ symbol too.
Inside the function, $ will only refer to the jQuery object.
Refer http://docs.jquery.com/Plugins/Authoring
It is to make sure $ means the same thing as jQuery. Other libraries may change what $ means, so this is needed.
function($) is called with jQuery as an argument, therefore $ gets set to jQuery within the function.
That is a self executing function, think of it like document.ready function in jQuery, except that this function will fire once its loaded.
(function(){}) will declare the function, but by adding () this can be fired immediately.
You can pass parameter s to this function as well. $ is actually an alias of jQuery, so to make sure that you are using jQuery, this is passed as a parameter and aliased as $ which is the convention.
(function(myAwesomePlugin){})(jQuery);
This is also valid. You can use it like myAwesomePlugin("#id").click() ...
basically it’s an anonymous function that lets jQuery play nicely with other javascript libraries that might have $ variable/function. It is executed as soon as the DOM is parsed and is invoked in order of appearance if there are multiple appearances. At this point the document is however not displayed, its just parsed.
Apart from what has been said already, this self-executing function encapsulates all variables and other functions, so the main (window) namespace remains unpolluted as all variables and functions are 'local'.
I've seen the next way of writing self-invoking functions:
(function (app) {
app.foo = {
bar: function(){}
};
}(App));
Where App is a global object.
I wonder, why do we need to pass App as a param into a function? Why don't just use this:
(function () {
App.foo = {
bar: function(){}
};
}());
I see only one advantage of using the first way. If we for some reason rename the App object, then we can easily rename the param in brackets and our code will work as it works. But in case of the second way we will probably need to rename App in all places where we use it.
Are there other differences?
It means that the contents of the function – with regards to the app identifier – are agnostic to the global (or parent) scope.
One of the scenarios in which this is done is, for example, with jQuery, when you don't want to assume that the jQuery object is called $ (e.g. if no-conflict mode is on), but you do want to call it by that name. Passing it through an anonymous function like this (i.e. (function($) {})(jQuery)) allows you to generate a locally-scoped alias that doesn't interfere with the external meaning of the name $ in the parent/global scope.
The other answers explain the benefit of having a locally scoped copy. There are a few other benefits too:
As a micro-optimization it reduces scope lookups (it's less expensive to find a local var than a global one).
It can help in the minification process as all your params are reduce to single letter named vars.
It gives you a pseudo dependency management technique...in your example, you know your code is dependent on App.
For example, many libraries use the "$" character as a shortcut for their main function (e.g. JQuery). This is convenient, but can cause a clash when using multiple libraries. So, you could pass JQuery in like this:
(function($) {
// Code
var nav = $('#nav');
// More code
})(JQuery);
That way, you can still use the convenient shortcut, but you can also avoid clashes (as long as you also configure the libraries not to use the "$" shortcut).
You can also use it to redefine global variables locally to ensure they contain whay you expect:
(function($, undefined) { ... })(jQuery);
Where undefined is now the expected undefined. Also see: What is the purpose of passing-in undefined?
Most other uses are well covered in the other answers.
I have got a function, inside which are some simple expressions, adding nums, appending doms, etc.
Since I only have to call it once, so an anonymous function could do it. But which way should I choose and what's the difference?
1: Shorthand for $(document).ready() {}) I seen this a lot,
$(function(){
var something;
++something;
});
2: Found in jquery plugins. Is it binded to $(document).ready() too?
(function ($) {
var something;
++something;
})(jQuery);
The second one is not bound to the ready event.
In detail. This:
$(function(){ /* ... */ });
needs a variable $ defined. Usually this variable exists when jQuery is loaded and points to the jQuery function.
Subsequently, when you call the jQuery function with a function argument, jQuery is binding this function argument to the ready event. The above is equivalent to
jQuery(function(){ /* ... */ });
which is in turn a convenience shorthand for
jQuery(document).ready(function(){ /* ... */ });
Your second code snippet
(function ($) { /* ... */ })(jQuery);
does not rely on $ being defined or pointing to jQuery() (this can happen if multiple JS frameworks are loaded in parallel).
To still have the convenience of $ within a certain region of code, it creates a function within which $ is defined and points to jQuery(). However, it is not bound to a DOM event.
But this would be:
(function ($) {
$(function(){ /* ... */ });
})(jQuery);
This set-up is used to minimize the conflict between JS frameworks or other pieces of code that rely on $. jQuery plug-in authors use it to write plug-ins that work under many environments.
If you think the combined one is too complicated, jQuery also has a shorthand feature, which avoids variable conflicts and binds to document ready at the same time. But be careful, it only works on jQuery and has some downsides.
jQuery(function($) { /* some code that uses $ */ });
For more details, see these two articles:
Using jQuery with Other Libraries
.ready() # api.jquery.com (Aliasing the jQuery Namespace)
First
It's just shorthand
Second
You are sandboxing the use of $ to reduce conflicts with other libraries that use the $ shorthand.
$ is just a shortcut for the jQuery variable and is being passed into the inner function of the immediately invoked function...
Example
var outerVar = "something";
(function innerFunc(passedVar) {
passedVar === "something"; //true
})(outerVar);
innerFunc is executed and passed outerVar as its argument.
In your first example, the shorthand form is functionally identical to $(document).ready().
The second example is an immediately-invoked anonymous function (Thanks #Raynos for the correction: this is often called a self-invoking function; it is not one). The function is defined and executed in place, taking jQuery as its argument. One advantage of this approach is that variables declared within the function will not "pollute" the global (window) scope (as opposed, for example, to simply running that code outside the function). In your example, something is undefined outside the function.
Since jQuery is brought into the function as the argument $, $ is guaranteed to be jQuery within the body of that function -- even in cases where other libraries are using $ outside the function.
A useful side note: it's sometimes helpful to name "anonymous" functions. The, uh, functionality remains the same, but names can make it much easier to debug complex code.
(function superFunction (foo) { // naming this "superFunction"
var something = 10;
do_something_with( foo, something );
})(bar);
No it isn't, it is just a shorthand
No it isn't. This code makes sure that $ is really jQuery and not just another javascript library
From http://docs.jquery.com/Plugins/Authoring:
But wait! Where's my awesome dollar sign that I know and love? It's
still there, however to make sure that your plugin doesn't collide
with other libraries that might use the dollar sign, it's a best
practice to pass jQuery to a self executing function (closure) that
maps it to the dollar sign so it can't be overwritten by another
library in the scope of its execution.
Just combine the two styles.
jQuery(function($) {
// uses the real jQuery as $
// code
});
The first style was used to run some code when the DOM is ready.
The second style is used to ensure $ === jQuery and also to make $ a local variable (reduces lookup time by a tiny fraction)
I come here with quite a bunch of questions so lets start:
I want to know some things about the syntax used to make jquery as I wish to learn from it an use it for my self.
Question 1:
The starting of the jQuery library
(function( window, undefined ) {
// Define a local copy of jQuery
var jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context );
},
// Map over jQuery in case of overwrite
_jQuery = window.jQuery, .......
I would like to know what is meant by the bracket before the function like so "(function(window..." until now I have only declared my function like this
function myFunc(myArg1,myArg2){
//stuff
}
Question 2:
At the end of the jquery library I seem to understand that the $ sign is assigned in the global scope so that we can use the $ anywhere for the selectors, what i dont understand is that what does the "(window);" expression at the very end mean, and what purpose does it serve.
};
});
// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;
})(window);
My final question is, how can I go about making a globally accessable javascript Object of my own that I can use with lets say "ds.functionName(Arg1);" just like JQuery is used with the $ sign
Thank you :D
Question 1 and Question 2 are actually related. What they're doing is defining a function with the (function(params){...}) bit, and executing it straight away with the (window) bit, passing in window as the parameter. It looks quite odd, but it's a neat way of making sure you don't end up polluting the global namespace. If you define your function as function foo(){...}, it means that foo is a function in the global namespace (the window) anybody and everybody can call your function. Even worse, it means that nobody else can define a function foo in global without it trampling all over your function foo. Bad Things happen when this happens :-) 188663 has more info about this pattern.
Third question, jQuery does it nicely. What they're doing with the
// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;
means that you can call on jQuery or $, and it "just exists", it's way out there in the global scope. You're probably after the module or singleton pattern - 1479319 has some jolly good answers in this regard
1) This creates a closure, so that everything inside is local to this closure, only what the authors intend it exposed and in the global namespace.
2) The window expression is passing a a reference to the window object into that closure, it's the first parameter of function( window, undefined ) { up top, this causes it to immediately be invoked as well.
What you are looking at is called an Anonymous Function. Anonymous Functions can be passed around just like normal variables. They are also executed immediately once they are declared. It's quite a paradigm shift in understanding this concept. I'm sure there are some other explanations here on Stackoverflow that can explain them.
(...your code...)(argument);
So in your second example:
});
// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;
})(window);
the argument window is being passed into the anonymous function that started in example 1