Shared singleton pattern for sharing utility methods across pages

/ Published in: Other
Save to your folder(s)

Copy this code and paste it in your HTML
  1. /* A similar pattern to the module pattern is the “shared singleton” — create a singleton object for an application that can be used to share properties or methods between pages or inline frames.
  3. Here’s the start of a “my.js” script that every page or frame in an application could share: */
  5. if (typeof != “undefined”) {
  6. var my =; // shared singleton
  7. } else {
  9. var my = {};
  11. my.something …
  13. }
  15. /* The “parent” bit is so that the script can be used with iframes and still
  16. retain a reference to the same “my” instance. If a page is at the top, then parent points to itself.
  18. Every page or frame that imports “my.js” can share properties or methods with any other page. */

Report this snippet


RSS Icon Subscribe to comments

You need to login to post a comment.