Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript with new or not

Tags:

javascript

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 to the function. From firebug, it seems two objects are the same. And as I understand, both should enforce the singleton 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 () {
    }
  };
})();
like image 220
J.W. Avatar asked Jun 24 '11 11:06

J.W.


People also ask

Should you use new in JavaScript?

It is NOT 'bad' to use the new keyword. But if you forget it, you will be calling the object constructor as a regular function. If your constructor doesn't check its execution context then it won't notice that 'this' points to different object (ordinarily the global object) instead of the new instance.

What does () => mean in JavaScript?

It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.

Is new an operator in JavaScript?

The new operator is used for creating a user-defined object type instance of one of the builtin object types that has a constructor function.

What is new () in Java?

The new operator is used in Java to create new objects. It can also be used to create an array object. Let us first see the steps when creating an object from a class − Declaration − A variable declaration with a variable name with an object type. Instantiation − The 'new' keyword is used to create the object.


1 Answers

While the end result seems identical, how it got there and what it executed in is different.

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

In the end, they both return another object(your Singleton). It's just a slight difference in execution context.

To test this out, but an alert(this); right before the declaration of the privateVar variable.

@Tom Squires: That's not necessarily true and is poor practice not to declare your variables. A script with the "use strict"; directive does cause the JS engine to complain (assuming that the engine supports "use strict";

like image 176
Dino Gambone Avatar answered Oct 11 '22 16:10

Dino Gambone