Strange javascript code

I found this piece of code:

; 100% function($) { // WTF? var _true_ = true; // WTF? var _false_ = false; // WTF? var go = function(location, date) { location || (location = {}); var result = _false_; if (date && date.day) { result = geoService.go(location, date); } return !!result; } var process = function(func) { var args = [].prototype.slice.call(arguments, 1); return function() { return func.apply(this, args); } } // ... }(jQuery, undefined); 

Here: http://www.dofactory.com/products/javascript-jquery-design-pattern-framework (sorry, no id found on the page)

I do not understand what these parts do:

  • "100%" in the second line
  • destination var _true_ = true; and var _false_ = false; in 3-4 lines

I'm curious what their purpose is.

+6
source share
2 answers

"100%" in the second line

This is the number 100 followed by the module operator. It is not used for anything (since the result is not fixed), except to force the right side to be considered as an expression of a function instead of declaring a function.

This is a very unusual and unintuitive approach that I have never seen before.

Typically, wrap a function expression in parens or precede it with an operator.

var true = true; and var false = false; tasks in 3-4 rows

The author seems to be trying to draw attention to the use of true and false by copying them into variables that include non-alpha-numeric characters in the name instead of using literals. Again, this is very strange, and not what I have ever seen.

+9
source

This seems to be a collection of misused “best practices” that did not lead to exceptions, but definitely strange and obscure. Look at the second and last lines. Best practice is used exactly the opposite:

 (function ($, undefined){ // do the stuff })(jQuery); 

undefined here will be real undefined because there is no second argument when calling the function. But what on Earth could be the reason to pass the argument "undefined" to a function and not use it? This is like a prank.

The same applies to the 5 lines: it looks (and actually acts) as a "default argument", which is assigned, but done in a strange way (traditionally and, more obviously, it is used as location = location || {}; ). I believe that only reasons to write in this way can be confusing, joking, or misunderstanding.

The same thing happens with 100% . You can use any operators to specify a function expression. The most common way is to use parentheses. But often you can also meet:

 !function(){ }(); 

or:

 +function(){ }(); 

but you can also write

 42 * function(){ }(); 

all this works the same way, only the brackets are the most obvious and common.

+6
source

Source: https://habr.com/ru/post/981513/


All Articles