I am just starting out with writing jQuery plugins. I wrote three small plugins but I have been simply copying the line into all my plugins without actually knowing what it means. Can someone tell me a little more about these? Perhaps an explanation will come in handy someday when writing a framework :)
What does this do? (I know it extends jQuery somehow but is there anything else interesting to know about this)
(function($) {
})(jQuery);
What is the difference between the following two ways of writing a plugin:
Type 1:
(function($) {
$.fn.jPluginName = {
},
$.fn.jPluginName.defaults = {
}
})(jQuery);
Type 2:
(function($) {
$.jPluginName = {
}
})(jQuery);
Type 3:
(function($){
//Attach this new method to jQuery
$.fn.extend({
var defaults = {
}
var options = $.extend(defaults, options);
//This is where you write your plugin's name
pluginname: function() {
//Iterate over the current set of matched elements
return this.each(function() {
//code to be inserted here
});
}
});
})(jQuery);
I could be way off here and maybe all mean the same thing. I am confused. In some cases, this doesn't seem to be working in a plugin that I was writing using Type 1. So far, Type 3 seems the most elegant to me but I'd like to know about the others as well.
Firstly, a code block that looks like (function(){})() is merely a function that is executed in place. Let's break it down a little.
1. (
2. function(){}
3. )
4. ()
Line 2 is a plain function, wrapped in parenthesis to tell the runtime to return the function to the parent scope, once it's returned the function is executed using line 4, maybe reading through these steps will help
1. function(){ .. }
2. (1)
3. 2()
You can see that 1 is the declaration, 2 is returning the function and 3 is just executing the function.
An example of how it would be used.
(function(doc){
doc.location = '/';
})(document);//This is passed into the function above
As for the other questions about the plugins:
Type 1: This is not a actually a plugin, it's an object passed as a function, as plugins tend to be functions.
Type 2: This is again not a plugin as it does not extend the $.fn object. It's just an extenstion of the jQuery core, although the outcome is the same. This is if you want to add traversing functions such as toArray and so on.
Type 3: This is the best method to add a plugin, the extended prototype of jQuery takes an object holding your plugin name and function and adds it to the plugin library for you.
At the most basic level, something of the form (function(){...})() is a function literal that is executed immediately. What this means is that you have defined a function and you are calling it immediately.
This form is useful for information hiding and encapsulation since anything you define inside that function remains local to that function and inaccessible from the outside world (unless you specifically expose it - usually via a returned object literal).
A variation of this basic form is what you see in jQuery plugins (or in this module pattern in general). Hence:
(function($) {
...
})(jQuery);
Which means you're passing in a reference to the actual jQuery object, but it's known as $ within the scope of the function literal.
Type 1 isn't really a plugin. You're simply assigning an object literal to jQuery.fn. Typically you assign a function to jQuery.fn as plugins are usually just functions.
Type 2 is similar to Type 1; you aren't really creating a plugin here. You're simply adding an object literal to jQuery.fn.
Type 3 is a plugin, but it's not the best or easiest way to create one.
To understand more about this, take a look at this similar question and answer. Also, this page goes into some detail about authoring plugins.
A little help:
// an anonymous function
(function () { console.log('allo') });
// a self invoked anonymous function
(function () { console.log('allo') })();
// a self invoked anonymous function with a parameter called "$"
var jQuery = 'I\'m not jQuery.';
(function ($) { console.log($) })(jQuery);
Just small addition to explanation
This structure (function() {})(); is called IIFE (Immediately Invoked Function Expression), it will be executed immediately, when the interpreter will reach this line. So when you're writing these rows:
(function($) {
// do something
})(jQuery);
this means, that the interpreter will invoke the function immediately, and will pass jQuery as a parameter, which will be used inside the function as $.
Actually, this example helped me to understand what does (function($) {})(jQuery); mean.
Consider this:
// Clousure declaration (aka anonymous function)
var f = function(x) { return x*x; };
// And use of it
console.log( f(2) ); // Gives: 4
// An inline version (immediately invoked)
console.log( (function(x) { return x*x; })(2) ); // Gives: 4
And now consider this:
jQuery is a variable holding jQuery object.
$ is a variable
name like any other (a, $b, a$b etc.) and it doesn't have any
special meaning like in PHP.
Knowing that we can take another look at our example:
var $f = function($) { return $*$; };
var jQuery = 2;
console.log( $f(jQuery) ); // Gives: 4
// An inline version (immediately invoked)
console.log( (function($) { return $*$; })(jQuery) ); // Gives: 4
Type 3, in order to work would have to look like this:
(function($){
//Attach this new method to jQuery
$.fn.extend({
//This is where you write your plugin's name
'pluginname': function(_options) {
// Put defaults inline, no need for another variable...
var options = $.extend({
'defaults': "go here..."
}, _options);
//Iterate over the current set of matched elements
return this.each(function() {
//code to be inserted here
});
}
});
})(jQuery);
I am unsure why someone would use extend over just directly setting the property in the jQuery prototype, it is doing the same exact thing only in more operations and more clutter.
Related
What are the difference among -
First :-
(function () {
var Book = 'hello';
}());
Second:-
(function () {
var Book = 'hello';
})();
First and second are similar some how in work..
Third :-
(function ($) {
var Book = 'hello';
})(jQuery);
What pattern I need to use and where in my coding.. Third module pattern I have seen while I was reading a article related to backboneJS.
What I understood from Third one "self executing function with the argument “jQuery”" ....
Can any please give me some idea about Immediately Invoked Function Expressions (IIFE).
Thanks !!
In all cases you are doing an anonymous function. I think 1 is the same as 2.
In the third case you are passing jQuery as an argument. This is done when you want to encapsulate jQuery within your function's scope.
For instance, in your application, jQuery var could be jQuery. But within your anonymous function you may want to use it as $.
(function ($) {
//Here jQuery is $
var Book = $(document.body).text();
})(jQuery);
//Out of your function, you user jQuery as jQuery (in this example)
var Book = jQuery(document.body).text();
This is called a closure to avoid conflicts with other libraries such as mootools which are using $. This way you can ensure to use $ in that function with passing jQuery as a param.
(function ($) {
$(function () { // Here in this block you can use '$' in place of jQuery
.......
});
})(jQuery); //<----passing jquery to avoid any conflict with other libraries.
Immediately-invoked function expressions (IIFE) is one of the core JavaScript features. Its main aim is not to clutter the namespaces with disposable functions and variables.
if you use a variable or a function only once, you don't need to make it available for the rest of the code (therefore you make a private access, for example). In case of functions, you may just let them be anonymous, just like the following:
(function(){
console.log("Hello symfony world!");
}());
Please check with this link
Furthermore here is a useful explanatory video in less than 7 minutes
As the other answers pointed out they are all self executing anonymous function or immediate anonymous functions.
The third example is use to create aliases for variables outside the function. This is a good way to prevent name conflicts and creating code where it's possible to easily change a module used in the function. It's essentially a form of dependency injection.
(function (doc, win, $, myModule) {
// Code
}(document, window, jQuery, window.MYAPP.myModule));
doc, win, $ and myModule are injected variables. With this pattern it's trivial to change any of the injected components. Like this
(function (doc, win, $, myModule) {
// Code
}(document, window, jQuery, window.MYAPP.myModule2)); //Use myModule2 instead myModule
Like every other answer has said, in the third function you are passing JQuery to the function.
I would like to take a moment and explain why the first two are the same.
When you create a function, the name of that function is really a function pointer. For instance, in function foo(){}, foo is a pointer to the function that you just made (which explains stuff like this). You dereference that pointer (and thus execute the function) by adding parenthesis at the end of the function name: foo().
So if we look at that code again, in number one, first you create the function:
function () {
var Book = 'hello';
}
And then you dereference it, effectively executing the function: ()
In the second example, you surround the entirety of the function creation in parenthesis:
(function () {
var Book = 'hello';
})
This ensures that you perform the creation operation before your next command, which is to dereference the function again: (). The parenthesis in this case are not really necessary, as the function will be created before it is executed anyway.
All three examples are Immediately Invoked Function Expressions (IIFE).
The only difference is that in the third example jQuery is being passed in as a variable allowing you to use it within the IIFE using its dollar naming convention. e.g.
(function ($) {
var Book = 'hello';
$('#bookelement').html(Book);
})(jQuery);
These all are self executing functions. Now days also known as Immediately Invoked Function Expressions (IIFE).
First two are exactly same with slightly different syntax and third is passing a parameter as jQuery object.
In fact, all three are self executing function's and ti really depends on what you are needing to do.
The only difference between is between 3. 1 and 2 are the same.
The difference with 3 is that you are passing a reference to jquery as an argument. Now all functions inside this annoyomus function have access to jque
All of these are example of self invoking function.
This will give you a clear view:-
var my_func = function(){
var internal_var = "Hello";
return internal_var;
};
var my_func2 = function(name){
var internal_var = "Hello";
return internal_var;
};
var long_var_name = "I can be some object or number or object or array";
var result1 = (my_func());
var result2 = (my_func)();
var result3 = (my_func2)(long_var_name);
console.log(result1, result2, result3);
Using this example you can compare it with the First, Second and Third method.
I am writing my first jQuery plugin, and I'm not entirely sure what should be inside the extension declaration and what shouldn't.
$.fn.myplugin = function () {
var somevar = this;
someFunc(somevar);
};
function someFunc() {/*doSomethin'*/};
OR
$.fn.myplugin = function () {
var somevar = this;
someFunc(somevar);
function someFunc() {/*doSomethin'*/};
};
I'd use the first option because:
It doesn't have any negative side effects.
That's where you are wrong. If you are working with different libraries you risk overwriting someone elses someFunc(), possibly breaking whatever they were trying to do for you. A safer way would be to wrap a closure around your code.
(function(){
$.fn.myplugin = function () {
var somevar = this;
someFunc(somevar);
};
function someFunc() {/*doSomethin'*/};
/* Do whatever other things you need someFunc/myplugin for */
})();
This way your someFunc is shielded from the global namespace.
Alternatively what you might be looking to do is to expose the method of the object to the outside world. Take following example:
$.fn.dog = function () {
this.bark = function() {alert("Woof");};
return this;
};
var $max = new $('#myDogMax').dog();
$max.bark();
This keeps the function within the context of your object but makes it possible to access it cleanly from the outside. Although this usually means that the method is somehow related to the object. It would make little sense to write a bark() function globally, as it are usually dogs that tend do it and not browser windows.
In your first method, you end up polluting the global scope adding someFunc(). The second method doesn't.
However, that doesn't automatically mean the second method is better. If you enclose the first method in a closure, it basically ends up being the exact same thing, and comes down to personal preference.
Here, it might even be better to use the first method (in a closure), so that if you have multiple jQuery extensions in a single JS file, they can share this base function.
What are the difference among -
First :-
(function () {
var Book = 'hello';
}());
Second:-
(function () {
var Book = 'hello';
})();
First and second are similar some how in work..
Third :-
(function ($) {
var Book = 'hello';
})(jQuery);
What pattern I need to use and where in my coding.. Third module pattern I have seen while I was reading a article related to backboneJS.
What I understood from Third one "self executing function with the argument “jQuery”" ....
Can any please give me some idea about Immediately Invoked Function Expressions (IIFE).
Thanks !!
In all cases you are doing an anonymous function. I think 1 is the same as 2.
In the third case you are passing jQuery as an argument. This is done when you want to encapsulate jQuery within your function's scope.
For instance, in your application, jQuery var could be jQuery. But within your anonymous function you may want to use it as $.
(function ($) {
//Here jQuery is $
var Book = $(document.body).text();
})(jQuery);
//Out of your function, you user jQuery as jQuery (in this example)
var Book = jQuery(document.body).text();
This is called a closure to avoid conflicts with other libraries such as mootools which are using $. This way you can ensure to use $ in that function with passing jQuery as a param.
(function ($) {
$(function () { // Here in this block you can use '$' in place of jQuery
.......
});
})(jQuery); //<----passing jquery to avoid any conflict with other libraries.
Immediately-invoked function expressions (IIFE) is one of the core JavaScript features. Its main aim is not to clutter the namespaces with disposable functions and variables.
if you use a variable or a function only once, you don't need to make it available for the rest of the code (therefore you make a private access, for example). In case of functions, you may just let them be anonymous, just like the following:
(function(){
console.log("Hello symfony world!");
}());
Please check with this link
Furthermore here is a useful explanatory video in less than 7 minutes
As the other answers pointed out they are all self executing anonymous function or immediate anonymous functions.
The third example is use to create aliases for variables outside the function. This is a good way to prevent name conflicts and creating code where it's possible to easily change a module used in the function. It's essentially a form of dependency injection.
(function (doc, win, $, myModule) {
// Code
}(document, window, jQuery, window.MYAPP.myModule));
doc, win, $ and myModule are injected variables. With this pattern it's trivial to change any of the injected components. Like this
(function (doc, win, $, myModule) {
// Code
}(document, window, jQuery, window.MYAPP.myModule2)); //Use myModule2 instead myModule
Like every other answer has said, in the third function you are passing JQuery to the function.
I would like to take a moment and explain why the first two are the same.
When you create a function, the name of that function is really a function pointer. For instance, in function foo(){}, foo is a pointer to the function that you just made (which explains stuff like this). You dereference that pointer (and thus execute the function) by adding parenthesis at the end of the function name: foo().
So if we look at that code again, in number one, first you create the function:
function () {
var Book = 'hello';
}
And then you dereference it, effectively executing the function: ()
In the second example, you surround the entirety of the function creation in parenthesis:
(function () {
var Book = 'hello';
})
This ensures that you perform the creation operation before your next command, which is to dereference the function again: (). The parenthesis in this case are not really necessary, as the function will be created before it is executed anyway.
All three examples are Immediately Invoked Function Expressions (IIFE).
The only difference is that in the third example jQuery is being passed in as a variable allowing you to use it within the IIFE using its dollar naming convention. e.g.
(function ($) {
var Book = 'hello';
$('#bookelement').html(Book);
})(jQuery);
These all are self executing functions. Now days also known as Immediately Invoked Function Expressions (IIFE).
First two are exactly same with slightly different syntax and third is passing a parameter as jQuery object.
In fact, all three are self executing function's and ti really depends on what you are needing to do.
The only difference between is between 3. 1 and 2 are the same.
The difference with 3 is that you are passing a reference to jquery as an argument. Now all functions inside this annoyomus function have access to jque
All of these are example of self invoking function.
This will give you a clear view:-
var my_func = function(){
var internal_var = "Hello";
return internal_var;
};
var my_func2 = function(name){
var internal_var = "Hello";
return internal_var;
};
var long_var_name = "I can be some object or number or object or array";
var result1 = (my_func());
var result2 = (my_func)();
var result3 = (my_func2)(long_var_name);
console.log(result1, result2, result3);
Using this example you can compare it with the First, Second and Third method.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What does this “(function(){});”, a function inside brackets, mean in javascript?
javascript anonymous function
(function())()
this is used in many js library like jquery,YUi
Thats called Module Pattern. The idea is to have an encapsulated module, that cannot conflict with any other modules you or someone else has created. You can create public and private methods within that module.
See: Js Pattern
I'm not sure what (function())() means, but I'll work on the assumption that you meant (function() { … })(). It is roughly the same as:
f = function() { … }; // Define a function.
f(); // Call it.
The only difference is that it does so without requiring a variable.
It is an anonymous self executing function. It is anonymous, because it is not named, and self executing, so it runs (there would be no other way to run an un-named function).
It is particularly useful to enclose a discreet module of code, because it acts as a closure preventing variables leaking into the global namespace.
You're immediately calling an anonymus function with a specific parameter.
An example:
(function(name){ alert(name); })('peter') This alerts "peter".
In the case of jQuery you might pass jQuery as a parameter and use $ in your function. So you can still use jQuery in noConflict-mode but use the handy $:
jQuery.noConflict() (function($){ var obj = $('<div/>', { id: 'someId' }); })(jQuery)
It simply executes the code wrapped in parentheses right away (the first block returns a function, the second pair of parens executes it).
Take for instance these two snippets:
function foo() {
print 'foo';
}
(function() {
print 'foo';
})();
The first won't do anything until you call foo(); whereas the second will print 'foo' right away.
I'd like something equivalent to this code, except I don't want my_func to be called when my_var is defined. I want to call my_var() later on in the code with the original argument ('called!') preserved.
function my_func(first_arg) {
alert(first_arg);
};
var my_var = my_func('called!');
How?
Your function will be called when the variable is initialized (and the variable will then hold the output of your function, which isn't what you want). Why not make another function that returns the output of your function?
I'm bad at explaining things, so here's some code to stare at:
var my_var = function() { return my_func('called!'); };
You might be looking for something like Function.prototype.bind, which allows you to bind a function with arguments to a particular context. Basically, it allows you to do this:
function myFunc(firstArg, secondArg) {
alert(firstArg + secondArg);
};
var myVar = myFunc.bind(null, 'called!');
myVar(' - from myVar!');
// result is alert with -> "called! - from myVar"
It's not in older browsers, but the link above has a compatibility implementation to make it work for this particular scenario.
The straightforward way to implement this would be wrapping a call to your function with an argumentless anonymous function:
var my_var = new function() {
my_func('called!');
}
ECMAScript 5th Edition introduces the Function.bind method that implements partial application (or more specifically currying), that would let you write this the following way:
var my_var = my_func.bind(undefined, 'called!');
(The undefined is there because the first parameter of bind() binds a value to the this "parameter".)
Function.bind() is relatively recent and not widely implemented. The Mozilla documentation includes a simple shim you could use to get most of the functionality. John Resig also has a blog post with a different implementation of partial application. It might also be available in one of the many many JS libraries.
Make a new function!
function my_func(first_arg) {
alert(first_arg);
};
var my_var = function() {
my_func('called!');
}
Just need the function to return a function:
function my_func(first_arg) {
return function(){alert(first_arg);}
};
var my_var = my_func('called!');