0

We have 2 Singleton:

let Singleton = (() => {
  let instance;

  function init() {
    return instance || (instance = this);
  }
  return init;
})();

let s = new Singleton();
let s2 = new Singleton();

console.log(s == s2);

let Singleton2 = (() => {
  let instance;
  let init = () => {
    return instance || (instance = this);
  }
  return init;
})();

let s1 = new Singleton2();
let s12 = new Singleton2();

console.log(s1 == s12);

first one works like it suppose to, but second one give me: Uncaught TypeError: Singleton2 is not a constructor

can some body tell me why the second Singleton is not a constructor? thank you for your time.

E. Sundin
  • 4,103
  • 21
  • 30
  • Don't use constructor functions for singleton objects anyway. Just write `let s1 = {…}; let s12 = s1;`. Use the IIFE module pattern if you need a private scope. – Bergi Mar 21 '18 at 22:57

1 Answers1

0

It's because you're using an Arrow function on the second one. It treats this differently.

An arrow function expression has a shorter syntax than a function expression and does not have its own this, arguments, super, or new.target. These function expressions are best suited for non-method functions, and they cannot be used as constructors.

E. Sundin
  • 4,103
  • 21
  • 30