0

There is a jquery.query-object.js extension which is implemented this way:

new function(settings) { 
  var $separator = settings.separator;
  ...

  jQuery.query = new function() {
   ...
  }
}

.$query object provides you some services, but magic behind passing settings object makes me perplexed. I got to write something like this next to jquery.query-object.js file reference:

<script type="text/javascript">
    jQuery.query = { separator: '|' };
</script>

I can not marry this two parts in my brain. Who can explain me please on how javascript/JQuery managed to handle above-mentioned syntax to run new function(settings) ? What confuses me is that code like var $separator = settings.separator; declared out of jQuery.query scope.

YMC
  • 4,925
  • 7
  • 53
  • 83
  • `What confuses me is ...` that just makes it not globally available. not quite sure what's confusing about that specifically. – Kevin B Aug 14 '14 at 18:55
  • 1
    [`new function` is an antipattern](http://stackoverflow.com/q/10406552/1048572). I wouldn't expect the rest of the code to be much better. – Bergi Aug 14 '14 at 18:55

1 Answers1

1

In case you mean this file, there new function is just an abuse of the new keyword to create an IIFE with a local scope - similar to how the exclamation mark can be used. This abuse is even worse when doing jQuery.query = new function() { … }, where the IIFE actually returns a new queryObject(location.search, location.hash); as in the revealing module pattern.

What confuses me is that code like var $separator = settings.separator; declared out of jQuery.query scope

Notice that the jQuery.query object doesn't have a scope, but the module IIFE that yielded it has. Every function defined within there has access to the local variables of that inner scope, but also can access the (local) variables of the parent scope. Of course, that additional inner scope is totally useless.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375