I know that $ is an alias to jQuery. Below code is passing an anonymous function to the $ function which can take a callback function.
$(document).ready(function() {
// ...
});
Perfect. It is simple and clear. But in one of the website I see below two files but could not understand what is it doing.
File 1
(function($, window, document, ns) {
"use strict";
...
...
})
($, window, document, Granite.author);
File 2
(function($,document) {
"use strict";
...
...
})(Granite.$, document);
Can anyone help me to understand what we are passing $, window, document, ns etc?
This is not necessarily a jQuery concept. It is creating a function and calling it immediatly.
Something like this:
(function (argument) {
console.log(argument)
})("This is being passed to the function")
Another way to do it using arrow functions would be
((argument) => { console.log(argument) })("This is being passed to the arrow function")
If you want a function that calling itself, you can define it between
(function hello(){
console.log("hello")
})()
This will automatically call the function and log the "hello".
Related
I have the external js file which has more functions.
I need to call these functions from angular controller.
For example: external.js
...
...
function fun() {
...
...
}
...
...
Controller: acccountController.js
myApp.controller('AddAccountController',function ($scope,AddAccountLoginServices,$location,localStorageService,$compile,toaster){
....
....
$scope.getLoginForm = function(siteId,name) {
...
...
fun(); // This function from external.js file
});
...
...
});
I have imported external.js before the acccountController.js. But it doesnt calling that function. And also i have not get any console error for this.
How to achieve this... Thanks in advance.
EDIT: gave wrong answer, my bad. the following example works.
your external file should like this:
var doSomething = (function () {
"use strict";
return {
test: (function () {
return 'test';
}()),
test2: (function () {
return console.log('test 2');
})
};
}());
and in your controller you call your scripts function:
console.log(doSomething.test);
or
doSomething.test2();
i learned something too, thanks ;)
As mentioned by #nilsK, you define a self invoking function. And then reference to it via window object. For example -
(function functionName(){
Do Something Here...
})();
And then,
window.functionName();
And if your are using AngularJS,
$window.functionName();
I have similar situation and I did not have to make it self invoking function. Including the external js file into the html and it worked fine.
Where is you call $scope.getLoginForm()?. I think you never call it. So fun() is not called, so you not see any thing. You need call $scope.getLoginForm(). Two way to call
In HTML <button ng-click="getLoginForm()"></button>
Or in Javascript $scope.getLoginForm()
Good luck !
You need to create a global instance of the function.
Add a line:
var abc= new funcName();
at the end of the File and you can use this line (var abc= new funcName();) in your controller to invoke any methods from this file by using abc.methodName.
In Appendix A, page 199, when discussing using "use strict", it goes like this:
If you want strict mode to apply to mulitple functions without needing
to write "use strict" multiple times, use immediate function
invocation:
//good
(function() {
"use strict";
function doSomething() {
// code
}
function doSomethingElse() {
// code
}
}());
My question is, if this is what the whole anonlymous function looks like, then probably there is no effect (to the rest) of invoking it immediately? Because only two functions are declared within the anonymous function but it's neither called from within there (so the two functions cannot make any side effects to the rest of the world), nor returned to the outside so their references are lost.
Probably, I just want to confirm, that the code snippet is only intended to show the use of "use strict", so it simply omitted either the calls to, or return of, these two functions?
Thanks,
/bruin
The idea is that the IIFE encloses all of your code, not just those functions.
I think you are correct. This example is not a complete one because it will never call the functions defined in it. The example is just meant to illustrate how to apply "use strict" across a specific set of functions. If you wanted to extend it a bit so that the functions are exported, you could do something like this:
var myModule = (function() {
"use strict";
function doSomething() {
// code
}
function doSomethingElse() {
// code
}
return {
doSomething: doSomething,
doSomethingElse: doSomethingElse
};
}());
myModule.doSomething();
myModule.doSomethingElse();
I'm trying to build a Javascript library that will provide some functionality for a JQuery Plugin I'm putting together.
I got the following skeleton code from searching online although I'm not quite sure how it all works (I do know it's a closure). I've added my functions via declarations.
(function(window, document, $) {
function func_1(){
return 1;
}
function func_2(){
return 2;
}
})(window, document, jQuery);
So I put the above code in a separate JS file and then source it in my HTML page, then I run try to run the function like so (Note: I have JQuery set up as well):
<script type="text/javascript">
$(document).ready(function() {
console.log(func_1());
});
</script>
However, I seem to be getting some errors in Firebug (ReferenceError: func_1 is not defined).
I have two questions:
How do I call my functions?!
I'd like to be able to call the functions in the following format: className.functionName(). How do I restructure the skeleton code to enable me do this and, say, call my function like this: Device.func_1()?
Thanks for your anticipated assistance.
The closure is used to hide internal functions from the rest of the code. You need to explicitly expose the public functions of the library:
var Device = (function(window, document, $) {
function func_1(){
return 1;
}
function func_2(){
return 2;
}
var internalDevice = {
func_1: func_1,
func_2: func_2
};
return internalDevice; // expose functionality to the rest of the code
})(window, document, jQuery);
The (function(window, document, $) {})(window, document, jQuery); part is called an immediately invoked function expression (IIFE). It's used to avoid leaking all the library functions into the global scope. Otherwise, if some other library had a func_1 function it would either be overwritten or overwrite your library's func_1.
The arguments to the function are used to control how the library can affect other parts of the code and relies on it. For example, someone might overwrite the window.$ library so that $ is no longer available everywhere in the code. But since you have a local reference in the closure you can still access it.
Alternatively to using the code above - returning an object - you could also assign your library directly to the global scope:
(function(window, document, $) {
...
window.Device = internalDevice; // expose functionality to the rest of the code
})(window, document, jQuery);
I can only answer question number two, but you can create that by doing this:
var Device = {
function func_1()
{
// your first function
},
function func_2()
{
// your second function
}
};
That way you can just call:
Device.func_1();
Hop that helps :)
When something is inside a closure the scope of it is changed to that closure. func_1 and func_2 can only be seen inside the anonymous function calling them and below.
On some JS code on some sites I see Javascript code such as this:
SomeName.init = (function () {
// some stuff
})();
I mean, this is not a jQuery plugin code such as this:
(function( $ ){
$.fn.myPlugin = function() {
// Do your awesome plugin stuff here
};
})( jQuery );
Then, what is it? and what is the resulting JS object?
It's a anonymous function, which doesn't leak variables to the global scope when declaring variables using var.
SomeName.init = (function () {
return 3.1415;
})();
SomeName.init is a number (3.1415), because () after the anonymous function declaration executes the function. There's no way to obtain the original function, unless defined within the anonymous function:
(function foo(){
//foo refers to this function
too = foo;
})();;
//foo is undefined
//too refers to the function, because `too` has been defined without var
The Module Pattern. And those two snippets have more in common than you think.
(function () {
// some stuff
})()
is a anonymous function that calls itself instantly. It's just a closure around the code inside to stop the variable scope becoming global.
Whatever the function returns.
(function() {
//...
})();
Is used as a way to namespace code, or declare self-executing constructors. The resulting object is whatever that self-executing function returns.
The second snippet doesn't return anything and there is no resulting JS object.
I need to call specific js function. The problem is many time runtime situation can come where another js file may contain same name function. But i need to be specific that which function i am suppose to call.
Function overloading is not my solution.
Thanks and regards,
Tanmay
you're going to have to do some reorganization of your resources and use namespacing where you can.
if you have a method named saySomething defined twice, you would move one of them to an object (whichever suits your needs better).
var myNS = new (function() {
this.saySomething = function() {
alert('hello!');
};
})();
and the other defintion can be moved into a different object or even left alone.
function saySomething() {
alert('derp!');
}
you can now call the saySomething method like
saySomething(); // derp!
myNS.saySomething(); // hello!
edit: since it was brought up in comments, this
var myNS = {
saySomething: function() {
alert('hello!');
}
};
is equivalent to the first code block, in simpler form (if i'm remembering correctly).
At least in firefox, when you have two functions with the same name, the second will overwrite the first one.
So, you can't call the first one.
Try it:
function a() {alert(1);}
function a() {alert(2);}
a(); // alerts '2'
See in jsfiddle.
In javascript, similarly named functions automatically override previous function defined with the exact same name.
Let's say your page includes 1.js and 2.js and both of them define the same function, for example say, display(). In this case, based on which js file is included the last, the definition of 'display()' in that file will override all other prior definitions.
I use function scope to limit the scope of variables and functions
Here is an example:
// existing function in JavaScript
function one() {
console.log('one');
}
one(); // outputs one
// inserting new JavaScript
(function() { // anonymous function wrapper
'use strict'; // ECMAScript-5
function one() {
console.log('two');
}
one(); // outputs two
})(); // end of anonymous function
one(); // outputs one
I hope that helps
:)