LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   Can you explain to me some strange javascript code? (http://www.linuxquestions.org/questions/programming-9/can-you-explain-to-me-some-strange-javascript-code-4175483995/)

S. Chapelin 11-09-2013 06:58 AM

Can you explain to me some strange javascript code?
 
I am playing around with HTML5 and javascript and have found a file called
Quote:

Hand.js: a polyfill for supporting pointer events on every browser
Being a linuxian, I am naturally curious how the code works. I have encountered at the beginning of the file this bit of voodo:
Code:

var HANDJS = HANDJS || {};
(function () {
// Code to the end of the file
})();

Can someone explain to me how these lines work and what they do?
It is seemingly a function enclosed in parentheses followed by parentheses. Why?
What is that weird name: function()? Shouldn't function be a reserved name?
I presume that the first line puts true or false into the var HANDJS so that the file is not loaded twice.

Guttorm 11-09-2013 07:31 AM

Hi

The first line sets HANDJS to an empty object if the value evaluates to 0. This is usually done to set it if the value is null. Parameters to a function will get a value of null if they're not spcefied, so code like this is usually used to set default values.

The rest is an anonymous function. They're usually used as callbacks to other functions, like this:

setTimeout(function(){alert("Hello")},3000);

But here it's just defined and called. (Notice the last () which means call that anonymous function). Any variables inside that function will be local when prefixed with "var", so it won't pollute or overwrite other variables with the same name. The purpose is to get a new namespace.

dugan 11-09-2013 01:25 PM

Quote:

Originally Posted by Guttorm (Post 5061281)
The first line sets HANDJS to an empty object if the value evaluates to 0. This is usually done to set it if the value is null. Parameters to a function will get a value of null if they're not spcefied, so code like this is usually used to set default values.

You meant "undefined", not "null", right?


All times are GMT -5. The time now is 08:13 AM.