Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8611197
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T04:18:50+00:00 2026-06-12T04:18:50+00:00

I came across this rather interesting way to create a JavaScript singleton that can

  • 0

I came across this rather interesting way to create a JavaScript singleton that can be instantiated with the new keyword, like var x = new SingletonClass(). I have a pretty good grasp of variable scope and closures, etc., but I’m having a hard time understanding exactly why this block of code works the way it does.

// EDIT: DO NOT USE this code; see the answers below
function SingletonClass() {
  this.instance = null;
  var things = [];

  function getInstance() {
    if (!this.instance) {
      this.instance = {
        add: function(thing) {
          things.push(thing);
        },
        list: function() {
          console.log(things.toString());
        }
      };
    }
    return this.instance;
  }

  return getInstance();
}

var obj1 = new SingletonClass();
obj1.add("apple");
obj1.list();  //"apple"

var obj2 = new SingletonClass();
obj2.add("banana");
obj1.list();  //"apple,banana"
obj2.list();  //"apple,banana"

obj1.add("carrot");
obj1.list();  //"apple,banana,carrot"
obj2.list();  //"apple,banana,carrot"

My intuition says that each time a new SingletonClass is instantiated, this refers to that fresh new object — but then since a totally separate object is returned by the constructor, I would figure this would just get discarded. But it hangs around. How? Why?

There’s some tiny little detail going on here that I’m missing. Can anybody shine some light on it?

EDIT: Turns out this code is bad. The reason why it “magically” seems to hold a reference to the instance is because it’s actually silently storing it in the global object. It’s bad practice at best, and undoubtedly bug-prone.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-12T04:18:51+00:00Added an answer on June 12, 2026 at 4:18 am

    Don’t confused by the this inside the function getInstance, that this is the global object window, so you are creating an object and assigned to the window object, and next time you call the constructor, you are checking whether window.instance is existing.

    The code this.instance = null; is meanless, just confusing you. Remove it won’t change anything.

    The below is from the MDN.

    When the code new foo(...) is executed, the following things happen:

    1. A new object is created, inheriting from foo.prototype.
    2. The constructor function foo is called with the specified arguments
      and this bound to the newly created object. new foo is equivalent to
      new foo(), i.e. if no argument list is specified, foo is called
      without arguments.
    3. The object returned by the constructor function becomes the result
      of the whole new expression.
      If the constructor function doesn’t
      explicitly return an object, the object created in step 1 is used
      instead. (Normally constructors don’t return a value, but they can
      choose to do so if they want to override the normal object creation
      process.)

    Note the step3, when you have return statement in constructor, the returned result will be the result of the new expression.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Came across this code: <?php require_once 'HTTP/Session/Container/DB.php'; $s = new HTTP_Session_Container_DB('mysql://user:password@localhost/db'); ini_get('session.auto_start') or session_start();
I came across this rather unusual usage of 'delete'. Just wanted to know if
I came across this comprehensive explanation of the new .NET TPL library recently, and
I came across this comparison chart that suggests that FMS costs about 4.5 grands
I came across something that I think rather strange. The test program int main(int
Recently I came across a gcc extension that I have found rather useful: __attribute__(cleanup)
I recently came across a CSS pseudo class that can do an effect for
I came across an interesting but rather annoying problem. I am trying to integrate
i came across this post http://www.webmasterworld.com/javascript/3066162.htm about how in javascript when you instantiate an
I just came across this in some code, and I'm rather confused. timer =

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.