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')};
The second one returns a new instance of the function, as if it was a constructor.
So, these are equivelent:
Traditional method:
Lazy one-liner.
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.