In client side javascript, whats the difference b/w
$(function(){
....
});
and
function myFunc() {
...
}
(Could not find relevant tutorials on Google)
The first is a DOM ready handler function used in jQuery (a JavaScript library). It is executed when the DOM is fully loaded. Whereas, the second is a simply defined function with name myFunc.
You can read more about JavaScript functions in MDN:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function.
They are totally different uses of function.
The first on calls function $() with parameter function() {}.
The second defines function myFunc.
$() is a shorthand for jQuery's document.ready syntax: Documentation
Code inside a $() will run when the dom has loaded enough to be accessed/manipulated.
The second example is just a normal function declaration and creates a function named myFunc that can be called with syntax myFunc() later.
Related
What is the difference in $?
Question:
What does $ mean in the next example?
JS:
jQuery(document).ready(function() {
console.log('loaded');
});
jQuery(document).ready(function($) {
console.log('loaded');
});
Can someone explain to me what is the difference between these 2 functions?
Thank you in advance
$ is normally the name of the jQuery constructor. That is to say, it is the name of a function that you call every time you want to make a jQuery object. For instance:
$('div')
It is normally a global variable, which means it is available throughout the page's Javascript. There is another variable jQuery, which normally points to exactly the same thing.
console.log($ === jQuery); // true
However, it is possible to set $ to something else. Perhaps you want to use $ to mean something different in your code. Or perhaps you're using Prototype as well, which also uses the $ symbol to point to a function.
This is why the jQuery.noConflict() method exists: it stops $ referring to jQuery.
However, many authors prefer to use $ to refer to the jQuery constructor, because it's much more concise and readable. jQuery provides a helpful feature that allows them to do this easily.
When you do jQuery(document).ready(function(), you are assigning an event handler. The function will be run when the event is fired. What we can do is reassign $ to refer to jQuery solely in the scope of that callback function. This is aided by jQuery: every $(document).ready callback function is called with the jQuery constructor as the first argument, so you can use whatever name you choose within the function.
For instance:
var $ = 'apples';
jQuery(document).ready(function() {
$('div'); // causes an error: "TypeError: string is not a function"
});
jQuery(document).ready(function($) {
$('div'); // works fine
});
This functionality is documented in the jQuery API for the ready method, in the section entitled "Aliasing the jQuery Namespace".
It's just the name of an argument.
See the documentation for ready:
the handler passed to the .ready() method can take an argument, which is passed the global jQuery object
Trying to figure out what this means in javascript.
(function(document) { ... } )(document);
It is isn't using jQuery, so is this just a javascript way of making this wait till document is ready to execute?
Thanks.
This won't wait for the document to be ready, this will execute the content of the function immediately. Putting the function definition in parenthesis makes it an expression, which returns a value being the function, making it directly executable. This pattern is called an Immediately-Invoked Function Expression (IIFE).
This is probably used in conjunction with a minifier like the Closure Compiler.
Inside the function, document is a local variable. This makes it possible for the minifier to reduce its name to a one or two character name.
Note also that all variables defined inside the function will be local : they won't leak in the global scope, which may be interesting if this is only part of the script.
This creates an anonymous function that takes a single argument, and immediately calls it passing document as the argument.
This:
function(document) { ... }
creates a function taking one paremeter.
This:
(function(document) { ... })
makes it (the code, not the function) a valid expression. See here.
This:
(function(document) { ... } )(document);
calls that function with document as a parameter.
It's a basic modularization pattern. In different environments you could've passed some other object instead of document, but nothing inside that function has to know bout it.
This is called self-executed function. It evaluates the anonymous function taking a parameter called document with that parameter passed in.
I've been making a program and I want to know the difference between starting two functions like so:
$(function () {
//content
});
and
function Name () {
//content
}
Also, why can't I name the first example? I tried changing the first example to the second type, and the function stopped working fully. I've used jQuery with the first example and everything was fine, but with a different example, the function stopped working.
So what's the difference?
$(function () {}); this is shortcut for $(document).ready(function(){});
while this:
function Name () {
//content
}
is standard javascript function.
http://api.jquery.com/ready/
http://www.w3.org/wiki/JavaScript_functions
The first is a function expression that is used for the jQuery ready event, while the second is a function.
Using $(function(){...}); is shorthand for $(document).ready(function(){...});.
The ready event happens when the document has completed loading, so the event handler will run automatically. A regular function doesn't run at all unless you call it.
You can naturally use a regular function instead of the function expression for the event handler:
function readyHandler() {
...
}
$(readyHandler); // or $(document).ready(readyHandler);
A function expression can be named, for example:
var x = function y() { ... };
However, the name of the function expression (y in the example) is not global, it's only usable inside the function itself. Also, the exact implementation of this differs between browsers, so you should avoid using it.
The first one is a so-called anonymous function. It gets executed on the document ready event
$(document).ready(...);
and is jQuery convention. Since you cannot call it directly, it has no / needs no name.
The second version is a standard function that you can call by name at any time.
If you change the first one to the second notation, it will no longer run at document ready automaticly. Safe way is to move the "worklaod" into a function with the second notation, and create a line with the first notation that calls the funciton. That way you have the best of both worlds: a separately callable function, and simple auto-execution.
The first one:
$(function () {
//content
});
is passing an anonymous function to the jQuery object $, equivalent to $(document).ready(function(){});
the second is just a JavaScript function named Name.
From HTML5 Mobile Boilerplate's helper.js:
(function(document){
//all stuff here
})(document);
What does this snippet do or when does it run?
This is a closure, it defines a method which takes an argument document and immediately calls it with document as the parameter.
It runs as soon as it's finished evaluating - so basically straight away.
It creates a temporary, anonymous function and calls it with an argument called document. Presumably it has some local variables that it is hiding from the enclosing scope.
This is a javascript function that executes immediately when the browser encounters it while parsing the page. The function takes one parameter, which is the window.document property (as passed in at the bottom of the function.
If you say:
(function(var1){/*stuff*/})(var2)
That immediately calls the function and passes var2 to the function. Note that the function is anonymous and cannot be called directly. You can read about anonymous functions in general and anonymous functions in Javascript here:
http://en.wikipedia.org/wiki/Anonymous_function#JavaScript
Is this jQuery code
(function(jQuery){
})(jQuery);
equivalent to
$(document).ready(function () {
});
If yes, what are the differences between the two? If not, what does the first do?
EDIT:
Thanks everybody. Most response are similar with different flavours and sample
They are not equivalent.
Your first example is an Immediately-Invoked Function Expression (IIFE). It creates a closure around locally defined variables.
Your second example specifies a function to execute when the DOM is fully loaded. It is used to ensure that all element nodes in the DOM are available before executing the enclosed code. This is also a closure.
Both examples use anonymous functions.
It is worth pointing out that it is good practice to use both of your examples, like so:
(function($){
// locally-scoped, DOM-is-NOT-Ready-code here.
$(function () {
// your locally-scoped, DOM-is-ready-code here.
});
}(jQuery)); // note that I've moved the invocation into the parens
// that contain the function. This makes JSLint happy!
Absolutely not, the first one is a self-executing anonymous function and the second is the ready handler.
(function(jQuery){
//jQuery in this scope is referencing whatever is passed-in
})(jQuery);
So, the jQuery inside of the function isn't necessarily the same jQuery outside the function. But you typically do not want to mix-n-match global variable names with local ones.
Take this example:
(function(obj) {
alert(obj);
})('Hello');
This defines a function, then immediately invokes it, passing in "Hello"
$(document).ready(function () {
});
is equivalent to this:
$(function() {
});
The first snippet is an immediately invoked anonymous function which creates a local scope:
(function() {
var x = 2;
})();
alert(x); // undefined
No. The first one isn't really doing much. Just separating any variables inside from the surrounding scope, and creating a local jQuery variable inside.
The second one passes a function that is run after the DOM is ready (in other words after the <body> has loaded).
A common equivalent to:
$(document).ready(function () {
});
is:
$(function () {
});
which does the same thing.
While this:
(function(jQuery){
})(jQuery);
is often written as:
(function($){
})(jQuery);
so that the $ variable is no longer a global variable. Useful if the global $ variable is already in use.
Not at all. The first one is a closure - a function that you create and then immediately call. However, typically you would combine the two like this:
(function($) {
// use the $ variable
$(document).ready(function(){
// ...
});
})(jQuery);
By creating the closure you are renaming "jQuery" to "$" just locally for that block of code. The reason why you use the closure syntax is so that you can use the $ variable even though it might not be defined as a jQuery object in the global scope (i.e. some JavaScript frameworks like prototype use $ as a variable).
Whenever you write a jQuery plugin you should enclose all jQuery code in this kind of closure so it doesn't interfere with any other JavaScript frameworks. If you aren't writing plugins and you don't use any other JavaScript frameworks you probably don't have to bother enclosing your code in a closure.