3

I was wondering if the following way of writing function in javascript are equal.

To me it seems they produce the same result, but in what they can be different?

First way:

(function(){
    alert('ciao')
})();

Second way:

new function bar(){alert('ciao')}; 
2
  • Clear duplicate. stackoverflow.com/questions/1140089/… (Could of milked this question :P ) Commented Sep 18, 2011 at 20:49
  • 3
    Tongue in cheek answer: The difference is that the second is bad form and the first is generally acceptable. Commented Sep 18, 2011 at 20:56

2 Answers 2

3

The second one returns a new instance of the function, as if it was a constructor.

So, these are equivelent:

Traditional method:

function bar() {
    this.x = 5;
};
var x = new bar();

Lazy one-liner.

var x = new function bar() { this.x = 5; };

The only difference is that you cannot reuse bar later.

If you don't believe me, try console.log(x.y); on both examples.

Your first example is an anonymous function which is not instantiated, it is just called.

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

Comments

2

The first one executes the function and returns the result of it. The second one executes the function and returns an object.

EDIT: example:

enter image description here

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.