Q:

How to create a constructor function in javascript so that if two instance created with 'new' keyword the value of instance1 === instance2 return true

I was finding a way, if I can make this code work. I cannot use prototype and I want to create the instance using "new" keyword only.
function Employee(name) {
    this.name = name;
}
var e1 = new Employee();
var e2 = new Employee();
e1 === e2; // Expected result should be true.

A:

If you want to use the new keyword and you want the result to be a singleton, then you can do something like this:

var Employee = (function () {
   var instance;
   return function Employee(name) {
      if (!instance) {
         this.name = name;
         instance = this;
      }
      return instance;
   }
})();

var a = new Employee('a');
var b = new Employee('b');

// They pass the === check
console.log('===', a === b);

// But they have the same name because they're the same object
console.log('a.name', a.name);
console.log('b.name', b.name);

// And changing one changes them both because, again, they're the same object
a.name = 'z';
console.log('a.name', a.name);
console.log('b.name', b.name);

Normally when you call a constructor, new creates a new object, which you can add to by accessing this, and then that newly created object is returned. However, if you explicitly return something from your constructor, then that object will be used instead of the one that new would normally create. So i've set up the code so that the constructor always returns the same instance, which i've then trapped inside an IIFE to make it "private".
But notice that since a and b are literally the same object, they both have the same name. In my case, the first name sticks and the second one is ignored. You could modify the code to make the second name overwrite the first one, but it's impossible for them to have different names while still meeting your requirements that a === b.

