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 []?

1

3 Answers 3

4

This creates an anonymous function and invokes it with

(jQuery.query || {})

as the parameter.

try

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

in firebug.

Sign up to request clarification or add additional context in comments.

2 Comments

But what is jQuery.query? Should this be defined somewhere else?
I mean jQuery.query is also used in the body. Does it mean something?
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.

4 Comments

Isn't it possible to invoke code by just writing it inline in Javascript?
I mean if I can write new function(x){alert(x);}("foo"); then can't I just write alert("foo");?
@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.)
Mark as answer then, perhaps? :)
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.