r/javascript • • Jan 13 '14

How to create Singleton objects in JavaScript

http://viralpatel.net/blogs/javascript-singleton-design-pattern/
0 Upvotes

6 comments sorted by

View all comments

9

u/[deleted] Jan 13 '14 edited Jan 13 '14

Ahem...

var singleton = (function() {
  var privateData = "foo";
  var privilegedMethod = function() {
    return privateData;
  };

  var why = {
    not: "just",
    create: "a",
    literal: "object",
    with: privilegedMethod
  };

  return why;
}());

console.log(singleton.privateData); // => undefined
console.log(singleton.with()); // => "foo"

1

u/cwmma Jan 13 '14

If you did Object.create instead of object literal notation it would have a prototype.

If we're going all out for over engineering an iife