Javascript with new or not

I have the following function

var myInstance = (function() { var privateVar = 'Test'; function privateMethod () { // ... } return { // public interface publicMethod1: function () { // all private members are accesible here alert(privateVar); }, publicMethod2: function () { } }; })(); 

what's the difference if i add a new feature. From firebug, it seems the two objects are the same. And, as I understand it, both should provide a syntax pattern.

 var myInstance = new (function() { var privateVar = 'Test'; function privateMethod () { // ... } return { // public interface publicMethod1: function () { // all private members are accesible here alert(privateVar); }, publicMethod2: function () { } }; })(); 
+6
source share
1 answer

While the end result seems identical, how did he get there and what did he do in another.

The first version performs an anonymous function with this in the context of the window object. The second version performs an anonymous function, but this is in the context of a new empty object.

In the end, they both return another object (your Singleton). This is just a small difference in the context of execution.

To check this out, but alert(this); before declaring a privateVar variable.

@Tom Squires: This is not necessarily true and it is bad practice not to declare variables. A script with the "use strict"; directive "use strict"; makes the JS engine complain (assuming the engine supports "use strict" ;

+7
source

All Articles