2

The code sample is here.

The big code chunk starts with

new function(settings) {

and ends with

}(jQuery.query || {}); // Pass in jQuery.query as settings object

What does this trick do?

Why does Eclipse find 2 errors here? Eclipse dislikes new at the beginning. May I just remove it? Also Eclipse wishes ] at the end to "to complete NewExpression".

What does this mean? How to write this with []?

PeeHaa
  • 71,436
  • 58
  • 190
  • 262
Dims
  • 47,675
  • 117
  • 331
  • 600
  • possible duplicate of [`new function()` with lower case "f" in JavaScript](http://stackoverflow.com/questions/2274695/new-function-with-lower-case-f-in-javascript) – Rob W Dec 19 '11 at 12:07

3 Answers3

4

This creates an anonymous function and invokes it with

(jQuery.query || {})

as the parameter.

try

new function(x){alert(x);}("foo");

in firebug.

MLN
  • 13,728
  • 1
  • 17
  • 15
3

It is one way of creating a self-invoking javascript function. It's simply a function that is declared and invoked in one swift flick of the wrist.

http://sparecycles.wordpress.com/2008/06/29/advanced-javascript/

What Eclipse is complaining about is not really clear. The syntax is completely valid - it might just be that Eclipse cannot handle it properly.

EDIT: The argument that is passed: (jQuery.query || {}) passes jQuery.query to the function. If jQuery.query is null, false, zero or undefineded (falsey), an empty object literal will be passed instead, avoiding a null reference.

Anders Marzi Tornblad
  • 18,896
  • 9
  • 51
  • 66
  • Isn't it possible to invoke code by just writing it inline in Javascript? – Dims Dec 19 '11 at 12:22
  • I mean if I can write `new function(x){alert(x);}("foo");` then can't I just write `alert("foo");`? – Dims Dec 19 '11 at 12:23
  • 2
    @Dims - putting code in an immediately executed function has the advantage that any working variables you create will have local scope in that function (and thus disappear when the function completes) rather than being added to the global scope, so you can keep a block of code self-contained. You wouldn't do it for just an alert since an alert isn't going to have any side effects. (There are some more obscure advantages in some situations, but I won't try to explain them here.) – nnnnnn Dec 19 '11 at 12:37
  • Mark as answer then, perhaps? :) – Anders Marzi Tornblad Dec 19 '11 at 17:54
1

The new function construction is defining a new function. It works in major browsers, but it is preferred to use slightly different syntax.

(function() {
    ...
})();

Here we define a function and then immediately call it. In your code, the function is also passed a parameter.

The Eclipse complaining is probably a bug.

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367