Having trouble understanding this definition of javaScript function - javascript

http://jsfiddle.net/sidonaldson/ZuPYM/
(function() {
if (window.DeviceOrientationEvent)
{
$("e").innerHTML = "DeviceOrientationEvent";
window.addEventListener('deviceorientation', function(e)
{
// y-axis - yaw
var g = e.gamma || 0;
// x-axis - tilt
var b = e.beta || 0;
// z=axis - swivel
var a = e.alpha || 0;
// degree north
var c = e.compassHeading || e.webkitCompassHeading || 0;
// accuracy in deg
var accuracy = e.compassAccuracy || e.webkitCompassAccuracy || 0;
deviceOrientationHandler(g, b, a, c, accuracy);
}, false);
}
else
{
$("e").innerHTML = "NOT SUPPORTED #FAIL";
}
})();
Why does the function have a format of (function(...) {...}) (); What is going on here I have never seen a function declared like this.
Is the $ use a variable name like a _ in other languages
How does this function keep on looping, in C++ you needed a while or for or recursion what is going on with the function('e').

1) why does the function have a format of (function(...) {...}) (); What is going on here I have never seen a function declared like this.
This is a so called IIFE(Instantly Invoked Function Expression), which is basically an unnamed function which gets called just when the compiler reaches its end.
Think of it as a simple named function:
function myFunc() {...my code...}
And then it is executed right after the declaration:
myFunc();
Now the IIFE:
(function() {...my code...})();
^--------------------------^^^
Parentheses to enclose the function, the last two are to invoke the function itself
2) is the $ use a variable name like a _ in other languages
Yes it is, but in this case it is a function which simply returns the element with id e(normally it is the jQuery library, a very common one).
3) how does this function keep on looping, in C++ you needed a while or for or recursion what is going on with the function('e').
The function doesn't loop, it executes just once.
EDIT: as #Rup pointed out, you could be referring to why the handler is executed every time the event is triggered. This is possible since the window.addEventListener function adds a handler to an event(in this case deviceOrientation) which will be called every time the event is triggered. For more information please refer to this page, MDN is the best place(IMHO) to get informations about JS.

This is an IIFE. Basically, this function will execute immediately, without being explicitly called. Once you are more comfortable with javascript, I would strongly recommend you to read the link for IIFE (Immediately Invoked Function Expressions)
$ is for jQuery. It is a javascript library for HTML manipulation among other things. In javascript, $ and _ and more non-alphanumeric characters are also quite frequently used to define variables. Generally, $ stands for jQuery (but you can use it for anything else also). Similarly, _ stands for underscore.js.
This function does not "keep on looping". It is a listener. It listens to the DeviceOrientationEvent event and executes only when the device orientation changes.
It seems you are very new to javascript. I'd recommend you get some experience in JS before diving into jQuery

The format you're talking about is called immediately-invoked function expression (IIFE). It is normally used in plugin / libraries definitions to make the declared function part of window/document or extend an existing object such as jquery.
$ is for jQuery, _ is for underscore.js, but it simply depends on what argument you're passing.
the function you're referring to is executed every time the event deviceorientation is fired. This is referred in javascript as a callback or a handler.

1) This is an anonymous function being called and executed inmediately.
(function(argumentList) {
// body
})(provideArguments);
2) $ is a global variable declared by the jQuery library.
3) if you use jQuery, you can directly affect all the results of your query. The library will loop for you. This code, for example, will select all anchor tags and foreach tag will execute the addClass method, putting the class "myClassName" to the results of the "query".
$('a').addClass('myClassName');

(function(...) {...}) ();
It means the code will be executed in the page directly.
$
This is the Jquery selector. cf : http://api.jquery.com/category/selectors/
e
This is an event object. cf : http://api.jquery.com/category/events/event-object/

Related

JavaScript examples, clarify the langue pattern design for functions with-in functions

I am learning JavaScript and becoming confused by the logic of the code examples. From codecademy. Why are there function set-ups in function calls?
I'm quite confused. I am moving from a simplified C-like langue.
The JavaScript example
var main = function(){
$('.article').click(function(){
$('.description').hide();
$(this).children('.description').show();
});
};
My understanding:
- main is a function name with a return type of var.
$('.article') is a element/object/or class object.
.click() is a call to a member function
But:
???:
.click(function(){
$('.description').hide();
$(this).children('.description').show();
});
This seems to be a newly on the spot created function to run When/If click() is activated or run.
The way I used to think is like this:
var *p_obj = $('.article');
var *p_obj = $('.description');
var do_click()
{
p_obj2.hide();
p_obj.children(p_obj2).show();
}
var main(){
p_obj.click(do_click);
}
Function main() looks at p_obj and calls click().
Click() evaluates to true/false and run the pointer_to function do_click().
Function do_click() looks at the p_obj2 and calls hide(), which performs an action of hiding the p_obj2.
Function do_click() also looks at p_obj and uses children to scope focus to p_obj2, then it runs show(), which preforms an action of displaying p_obj2.
I do realize my C-like example is wrong and odd. I realize my terminology is wrong or otherwise used incorrectly.
The way this design looks seems like I must write extended functionality on-the-spot for every call to .click(), so if-then .click() is run on 3 different items, I'm creating different extended functionality for each object. But I would normally create a single function that varies it's internal execution based on the object or condition click() calls it by.
This set-up seems alright if the code a relatively simple or short, but on-the-spot functional seems like overworking for longer code and code where the functionality repeats but the objects change.
Am I thinking about JavaScript functions with-in functions correctly and is this a design goal of the langue to add long repeating extended functions with-in functions?
Here, you should understand 2 things:
passing functions as arguments
anonymous functions
The first concept is particulary important because callbacks are popular in JavaScript, so let me explain it for callbacks. Imagine we have 2 functions getStuffFromWeb and processStuff. You probably expect that they are used like this:
var result = getStuffFromWeb();
processStuff(result);
But the issue here is waiting for getStuffFromWeb may take some time (the server is busy), so instead they are usually used in a "when you finish, call this function" manner, which is:
var getStuffFromWeb = function(params,callback) {
...
callback(result);
};
getStuffFromWeb(someParams,processStuff);
Well, in fact the structure of getStuffFromWeb will be different, most likely something like this:
var getStuffFromWeb = function(params,callback) {
requestObject.make_request(params)
.onSuccess(callback);
};
So when getStuffFromWeb is called, it starts to listen to response while the code after getStuffFromWeb(someParams,processStuff); goes on evaluating. When the response comes, it calls the callback function to process the data further using the procedure we have defined (processStuff).
The second concept is rather simple: you may of'course write smth like
var processStuff = function() {...};
var getStuffFromWeb = function(params,callback) {
requestObject.make_request(params)
.onSuccess(callback);
};
getStuffFromWeb(someParams,processStuff);
but if you use processStuff only once, why define a named function? Instead, you can just put the very same expression inside the onSuccess param like this:
var getStuffFromWeb = function(params) {
requestObject.make_request(params)
.onSuccess(function() {...});
};
getStuffFromWeb(someParams);
This looks exactly like if we took the value of processStuff and put it directly to the onSuccess's argument (and that's called anonymous function). And also we got rid of an extra argument of getStuffFromWeb.
So basically that's it.
Simple answer is that the second argument of click() requires a callback function.
This can be a named function passed as reference as in your p_obj.click(do_click); example or it can be an anonymous function with self contained logic. Anonymous functions are very common in javascript
It's the same thing just with 2 different ways of declaring the callback.
Note that the only time you would return anything from an event handler function would be to return false which effectively prevents the default browser event (url opening from href or form submit for examples) and stops event propagating up the DOM tree
main is a function name with a return type of var.
No. main is a variable which is assigned an anonymous function. The function name would go between the keyword function and the () containing the argument list.
It has no return statement so it returns undefined.
$('.article') is a element/object/or class object.
It is a call to the function $ with one argument. The return value is a jQuery object.
.click() is a call to a member function
Pretty much. In JavaScript we call any function that is the value of a property of an object as method.
This seems to be a newly on the spot created function
function () { } is a function expression. It creates a function, exactly like the one used to assign a value to main earlier. This question is worth reading for more on the subject.
When/If click() is activated or run.
The click function is called immediately. The new function is passed as an argument.
The purpose of the click function is to bind a click event handler so that when a click event hits the element later on, it will trigger the function passed as an argument.
I do realize my c -like example is wrong and odd. I realize my terminology is wrong or otherwise used incorrectly.
Leaving aside vagaries of syntax. The main difference here is that the click event handler function is that the event handler function is stored in an intermediary variable.
You can do that in JavaScript just as easily, and then reuse the function elsewhere in the code.
var main = function(){
function show_specific_description() {
$('.description').hide();
$(this).children('.description').show();
}
$('.article').click(show_specific_description);
show_specific_description.call($(".article").last()[0]);
};
main();
is this a design goal of the langue to add long repeating extended functions with-in functions?
No. Passing a function expression as an argument is a convenient way to be more concise when you don't want to reuse the function. It's not the only way to pass functions about.
main is currently a function.
It is possible to be overwritten (even to a different type). var is not the return type, it's a statement that main is a variable.
All values should be declared as variables, within the highest scope you intend them to be used (in JS, scope typically means functions, not blocks).
You have the right idea, suspecting that the function gets passed in, and called at a later point in time (and this is actually one of the harder parts for people to get, coming from certain other languages). You'll see this behaviour all through JS.
One key thing to keep in mind in this language (you haven't hit it yet, but you will) is that JS is lexically scoped.
function getInnerX () {
var x = 5;
function getX () {
return x;
};
return getX;
}
var x = 10;
var getX = getInnerX();
console.log(getX()); // 5
The function getX inside of getInnerX has access to the references around it, at the point where it's defined (not where it's called), and thus has live access to the inner x, even if its value changes over time.
This will be another important piece of understanding what you see going on in the language, especially in the case of callbacks.

Javascript vs jQuery Function Difference?

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.

JavaScript piece of code explanation

Check out this piece of JavaScript code:
(function (w, d) {
var loader = function () {
var s = d.createElement("script"), tag = d.getElementsByTagName("script")[0];
s.src = "https://example.org/script.js";
tag.parentNode.insertBefore(s,tag);
};
w.addEventListener ? w.addEventListener("load", loader, false) :
w.attachEvent("onload", loader);
}) (window, document);
Why did the author of this code use this method to include a script in the document?
And what is the usefulness of the line:
w.addEventListener ? w.addEventListener("load", loader, false) :
w.attachEvent("onload", loader);
Last point: I'm a JavaScript beginner, what is the (window, document) at the end?
The first question, the code checks to see if window.addEventListener is defined. If it is, it uses it, otherwise it uses window.attachEvent. This is for browser compatibility.
The 2nd question, this code is an anonymous function which takes 2 parameters, w and d. This function is immediately called, passing the parameters window and document.
The following addEventListener line is to register the function so that it gets called when the page finishes loading. Internet Explorer and Firefox (et al) use different functions to do this.
w.addEventListener ? w.addEventListener("load", loader, false) :
w.attachEvent("onload", loader);
In javascript a function is an object in and of itself. As such it's 'value' can be assigned to a variable or consumed immediately. To consume it immediately it must be wrapped in parentheses (otherwise it won't do what you want) and then call it like it were a regular function.
(function (w, d) { ... }) (window, document);
It's more obvious what is going on if we break it up across two lines.
var a = function(w, d){ ... };
a(window, document);
It was done this way to as to not pollute the global scope with temporary values or functions. Not to mention not trashing anyone else variables. This can be broken into two parts:
By encapsulating the code in a closure anything explicitly declared inside is in the closure's scope, not the global scope. var loader is in the closure's scope.
By consuming the closure immediately it won't be stored in a variable in the global scope. Since it was declared anonymously it won't exist as a named function in the global scope.
Firstly, w.addEventListener ?to make sure if the browser supported the addEventListener method of window
Secondly, (window, document) is just parameter call of anonymous function he wrote before function(w,d) {}
It looks like the author is waiting for the page to be fully loaded before attaching the script tag. addEventListener (DOM level 2) and attachEvent (Microsoft stuff) are more flexible ways of attaching events. The code is similar to saying w.onload = loader.
The last bit is passing arguments into the anonymous function, where they are named w and d. By putting the () at the end, the anonymous function is invoked right away.
So the function is wrapped in a closure. Which in turn means w = window and d = document.
When the method is called the it creates a function called loader which is the callback for one of the two possible event listener triggers (meaning, that'll be called when the load or onload event is called on the window).
The x ? y : z syntax is a shorthand if then else call.
If we expanded that out, it'd look like this:
if (w.addEventListener) {
w.addEventListener("load", loader, false);
} else {
w.attachEvent("onload", loader);
}
that statement is used cater the method for both IE and other browsers.
The author of this code is using an anonymous function wrapped in a closure to fire off the function, which registers a load event. The script on the page will not actually be loaded until the window's onload event fires.
The reason that the author may be delaying the script load may be to give the web page more time to render before actually loading in the other script. This is a great technique to load page content quickly while delaying the loading of resources that are not immediately needed.
The technique the author is using is an anonymous function wrapped in a closure. Picture this:
myFunction (window, document);
Now, I'm going to replace the function call with an anonymous function:
function(w, d) {
// do stuff
alert("w = " + w);
alert("d = " + d);
}
Now I'm going to cause that function to run immediately, without actually giving it a name. I'm also going to pass two parameters into that anonymous function:
( function(w, d) {
// do stuff
alert("w = " + w);
alert("d = " + d);
}) ("1234", "5678");
The output in this example would be:
w = 1234
d = 5678
If you watch the parentheses and match them up, the first outer parentheses matches the closing parentheses on the last line at character 2, that is the function name, and the following set of parentheses wrap the two values passed into the function as parameters.
This can be a tough concept to grasp at first; after you see it done a few times, it starts to make more sense.
Adding the script that way allows the author to include that script in the document without directly editing HTML files. Can also be used to dynamically load a script only when needed. (i.e. if you have a bunch of code to edit something on the page, you don't want to download it until the user actually clicks the edit button, so you don't waste bandwidth when it's not needed).
addEventListener and attachEvent are ways to trigger a function to be called when the page has finished loading. In this case, there's a function named loader
The reason for both is that some browsers support one and some support the other. I've been using jQuery long enough that I don't remember which is which.
(window, document) is a way to encapsulate those variables in scope and/or refer to them by shorthand w and d. The author is creating a function that expects those parameters, then passing both window and document as the arguments for them.
The closure also helps the author keep from having his script clash with other scripts on the page. Think of every variable declared in there like it's a private variable in other languages.
This is effectively the same as:
function RegisterEventListener(w, d) {
var loader = function () {
var s = d.createElement("script"), tag = d.getElementsByTagName("script")[0];
s.src = "https://example.org/script.js";
tag.parentNode.insertBefore(s,tag);
};
if (w.addEventListener) {
w.addEventListener("load", loader, false);
} else {
w.attachEvent("onload", loader);
}
}
RegisterEventListener(window, document);
The only real differences are:
If you define an anonymous function (using function () {};) without assigning it to anything it is only available for limited use (because there is no way to reference it). At the same time, anonymous functions also allow immediate execution (like the one in the code from your question function(a, b) {}(a, b);.
The condition ? true : false (tertiary operator) is just shorthand for writing simple if statements so it requires less typing to write out, but some people also see it as being less readable.
The window, document at the end of the first block of code are arguments to the anonymous function defined in the rest of the code block. Since Javascript is pretty much a functional language programmers are allowed to define these anonymous functions and even use them without giving them a name.
The block of code you pasted with the question mark is an example of infix notation, a language construct that fits this pattern: condition ? ifTrueExpression : ifFalseExpression. Where condition is true, the entire expression will be equal to ifTrueExpression. Otherwise, the entire expression will be equal to ifFalseExpression.
The use of infix notation you pasted is common in detecting which type of internet browser is being used. Although, I'm not sure which browser this block of code is trying to detect, its intent is to implement an event handler in a browser specific way.
I may be wrong, but this is the implementation used by Google with their analytics script.
This is called a closure, a function that is autoexecuted and enclose the variables inside, so they can't mess with your code.
This codes essentially creates a script tag and append this to the DOM before the first script tag it finds in the document.
The answer for the first question is about browser compatibility. some browsers use addEventListener and others attachEvent to attach events to elements in the page (in this case, the window) and it will lounch on the load event of the window (when all content is loaded, after the document is ready). Take a look at this for a more detailed answer: window.onload vs $(document).ready()
The second answer is simple. This are the parameters used in the closure (the auto calling function) and can be read in this way:
function anonymous(w, d) {
...
}
anonymous(window, document);

jQuery question: what does it really mean?

(function($, window, undefined){
... jquery code...
})(jQuery, window);
What does it really mean? Does it also mean $(document).ready()? Or just two different things?
There are already two answers but this is my guess on the missing end of the code:
(function ($, window, undefined) {
// ... jquery code...
})(jQuery, window);
Note: three parameters are expected but two are supplied.
What it basically does is:
gives a private scope inside curly braces, so any var declared inside is not visible outside
makes a private $ shortcut to jQuery without relying on this shortcut being set globally (eg. jQuery.noconflict() might have been called and this would still work)
makes a lexical window variable that would mean faster lookups for global variables
makes sure that undefined is indeed undefined in the scope between curly braces, even if someone has written something like undefined = "now it's defined"; in the global scope, because undefined can actually be redefined (this is a mistake of the language).
This pattern is known as immediately invoked function, or immediate function for short, or self-invoking anonymous function, or some other names. The basic idea is that:
(function (x, y) {
// ...
})(1, 2);
or:
(function (x, y) {
// ...
}(1, 2));
means the same as:
function myFunction (x, y) {
// ...
}
myFunction(1, 2);
but without the need to give any name to your function and pollute the namespace.
Going back to your question, this doesn't mean $(document).ready() or anything like that, but it means that you can use $(document).ready() inside instead of jQuery(document).ready() even if the $ shortcut is not available outside.
This example may actually explain it better, even if it isn't used anywhere:
(function (JQ, window, undefined) {
JQ(document).ready(function () {
// this is run when document is ready
});
})(jQuery, window);
Now instead of $ you can call jQuery as JQ and use JQ(document).ready() instead of $(document).ready() – it may not seem very useful but it shows what happens when you have a code like that.
As a side note I might add that thanks to this pattern you don't actually need variable declarations in the language but only function arguments. Instead of:
var x = 10;
alert(x * x * x);
you could use:
(function (x) {
alert(x * x * x);
})(10);
and indeed a function like this:
function square (x) {
// some code ...
var result = x * x;
return result;
}
is exactly equivalent to:
function square (x, result) {
// some code ...
result = x * x;
return result;
}
because of the hoisting mechanism in JavaScript that would make the result variable available (but undefined) even before the declaration and assignment in both cases (in the // some code ... part). This is often a source of confusion but is actually quite interesting and extremely powerful.
See also my other recently updated answer to the question:
Help understanding JavaScript global abatement techniques for more info on this subject.
(function($, window, undefined){
... jquery code...
})();
is different than
$(document).ready()
Paul Irish has a good video on 10 Things I Learned from the jQuery Source at 1:30 in he talks about the jquery source's self executing anonymous function and what the arguments mean
Like that it doesn't mean much at all (in addition a closing ) is missing). What you are probably looking at is something similar to this:
(function($, window){
// code
} )($, window);
This puts the code inside a new scope, so you can for example define variables without messing with the outside scope.
It also allows that you pass different things to the function, without having to change the code. For example if you use different JavaScript frameworks, and $ is not bound to jQuery, you can pass the alternative variable for jQuery instead, while you are still using the $ to refer to jQuery internally. Similar to that you could also pass a different window instance (for example from a popup).
I'm guessing the code actually looks like this:
(function($, window, undefined){
... jquery code...
})(jQuery, window);
Note the parenthesis at the end.
If this is the case, what's going on here is a self-executing anonymous function. The point of doing this is that any local variables or functions defined inside of that anonymous function will not pollute the global namespace.
#rsp has a great answer for this specific question.
For general background on this pattern also see http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth.

when to use Function in javascript?

I have been writing javascript for one or two months , I never used Function keyword , like Function.method(); when I define function , I simply define it as :
function fooBar () {};
Can you give me an example when using Function is more convenient ?
You shouldn't use the Function constructor so often, it basically uses code evaluation to build a function.
It requires string arguments, being the last argument the function body, and the previous ones will be the arguments of the new function itself, for example:
var add = new Function("a", "b", "return a + b;");
add(5,5) == 10;
When you should use it?
As I said not so often, I personally try to avoid them since they use code evaluation.
A thing to note is that no closures are created when functions are built in this way, which can be a good thing for some performance circumstances, for example to shorten the process of identifier resolution, but you should use them with care...
Every function in JavaScript is
actually a Function object.
Read Function
Function objects created with the
Function constructor are parsed when
the function is created. This is less
efficient than declaring a function
and calling it within your code,
because functions declared with the
function statement are parsed with the
rest of the code.
function view(){
document.getElementById('one').innerHTML="New Text here";
}
this function can you call from either keyboard events of mouse events

Categories