I have been working on a JS project and having never worked on a proper JS project before I installed JSHint to keep my JS in line. This lead to me looking at the "use strict" definition which lead to me reading about anonymous functions. Now I'm real confused. I don't know how to properly define my object.
I decided to look at some public js libraries (mainly Bootstrap) on how they do things.
This is the general pattern I see:
(function($) {
'use strict';
var MyObject = function() {
// ...
}
// Prototype methods
})(jQuery);
My questions is how do outside scripts then see the object? I want to be able to pass the object two ids from the initializer.
It's an IIFE (immediately invoking function expression).
It purposefully doesn't create global variables. It's used to keep the namespace clean. It's also passing the $ variable (defined as jQuery) as an argument so that it has access to jQuery without pulling in any other libraries that may use the $ sign that the user might be implementing.
I think you may want to look more into the constructor/module/prototypical inheritance patterns, and do some research in to why IIFEs are used (what situations they are good for/bad for).
If you want to use an IIFE and have a function that passes it arguments, or define the argument variables from inside (without polluting the namespace), you can just do it from inside your IIFE.
Off the top of my head example:
(function(){
var Foo = function(arg){
};
Foo.prototype.something = function(){
do something;
};
var Bar = function(){
do something;
return arg;
};
var baz = new Foo(bar());
baz.run();
//or
var ex = something you want to pass as an arg;
var baz = new Foo(ex);
baz.run();
})();
You can export MyObject in the following way
(function(window){
var MyObject = function....
MyObject.prototype. something...
window.MyObject=MyObject;
}(window));
More on constructor functions,prototype and inheritance here:https://stackoverflow.com/a/16063711/1641941
Related
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.
I've been wondering for a while - what can JavaScript closures be used for?
I know how to write them and I know how they work, but I just can't get the idea of how they can be used.
function closure() {
var name = "John";
function displayName() {
return 'Hello, ' + name;
}
return displayName;
}
So far I only found one use for them - encapsulating data, so it won't be visible outside the function.
But what else can they be used for? Should I write OOP with closures? Do I need to put all my code inside a closure so it wont mess the global scope?
Any clarifications are highly appreciated!
Can also be used to protect your code inside the colsure against naming conflicts between different libraries outside the closure. Ex whenever I create a JQuery plugin I create it as a self calling closure where I pass In "JQuery", but can safely refer to $ inside the closure because of the local scope of the named $ variable in my function definition. Even if there are other libraries using the $ variable for a different purpose
(function($){ //use $ safely inside the closure })
(jQuery);
Personally, besides obvious things like encapsulating or creating private contexts, I like Singleton JavaScript Design Pattern:
function Singleton() {
// cached instance
var instance = this;
//proceed as normal - adding some variables
this.variable1 = 1000;
this.variable2 = 3000000;
Singleton = function() {
return instance;
}
}
var singleton1 = new Singleton();
var singleton2 = new Singleton();
if(singleton1 === singleton2) {
console.log("Singleton works :)");
}
else {
console.log("Singleton doesn't work :/");
}
You can paste this code directly into Chrome JavaScript console.
Of course you can tweak it to suit your needs. There is also some drawback - you can overwrite Singleton function, and you will not be able to access instance anymore. But this is another problem.
I found it a long time ago in JavaScript Patterns book by Stoyan Stefanov (O'Reilly)
. Check this out as there are other useful design patterns and examples of closures application. According to this book:
You can use closure to store some private data, which is accessible by the returned function but not to the outside code.
What is the difference between
var module = (function(){
return {}
})()
and
(function(context){
var module = {}
context.module = module;
})(this)
A property of this is not equivalent to a variable. In the global scope (i.e. where this references window), they are similiar. Yet, for example they will have a different behavior when you try to delete them:
> this.module = {};
> delete this.module
true
> var module = {};
// cant be deleted
Apart from that, both snippets create an empty object, wrapped inside a closure where you could define local (private) variables/functions etc. In your second function the object is also assigned to the local variable module, but that could be done in the first one as well.
#Eric: Your approach, using the new operator, is similiar to the first one regarding the variable. However, it will create an instance of that anonymous function instead of returning a plain object. It will inherit properties from a custom prototype, so for example module.constructor will then point to the anonymous function (which cannot be garbage collected, but e.g. even reused to create a clone). I would not recommend to use this.
Top one is revealing module pattern. It lets you define private functions (as much as you can in javascript) and choose which ones are made public via the return call.
var module = (function(){
function foo() {}; // Public, since it's returned
function bar() {}; // Private, since it is not returned
return {
foo: foo
}
})();
The bottom one, as far as I can tell, just assigns an object literal to another object's namespace. It's probably the start of a singelton pattern.
(function(context){
var module = {};
context.module = module;
}(this)
The module could actually be defined with the revealing module pattern, hard to say since in your example it's just an object literal.
I'm reading more open source javascript frameworks and found more ways of how to create anonymous functions, but whats is different and best way?
(function() {
this.Lib = {};
}).call(this);
(function() {
var Lib = {}; window.Lib = Lib;
})();
(function(global) {
var Lib = {}; global.Lib = Lib;
})(global);
(function() {
this.Lib = {};
}).call(this);
Defines the Lib property of the Object it's called on, and is immediately called on this which is typically the window. It may instead refer to the Object that owns the method in which it is called.
(function() {
var Lib = {}; window.Lib = Lib;
})();
Defines the Lib property of window regardless of where it's called (although it's also called immediately).
(function(global) {
var Lib = {}; global.Lib = Lib;
})(global);
Defines the Lib property of the object passed to the function. It's called immediately, but will result in an error unless you've defined a value for global in the current scope. You might pass window or some namespacing Object to it.
These aren't actually different ways of defining "anonymous functions", they all use the standard way of doing this. These are different methods of assigning values to global (or effectively global) properties. In this sense, they are basically equivalent.
Of more significance would be, for instance, how they define methods and properties of the objects they return/construct/expose (that is, how they build Lib itself).
All of these functions return undefined and only the first could be usefully applied as a constructor (with the use of new), so it would seem they are nothing more than initializers for the frameworks.
All of them are effectively equivalent (but less efficient and more obfuscated) to:
var Lib = {};
Immediately invoked function expressions (IIFEs) are handy for contianing the scope of variables that don't need to be available more widely and conditionally creating objecs and methods, but they can be over used.
Note that in the last example, I think you mean:
(function(global) {
...
})(this);
Check out this question: Why do you need to invoke an anonymous function on the same line?
It contains a whole lot of information about anonymous functions. Check out this question as well: var functionName = function() {} vs function functionName() {}