Skip to content

Instantly share code, notes, and snippets.

@charlieroberts
Created September 28, 2017 17:41
Show Gist options
  • Select an option

  • Save charlieroberts/5708d78a3c31f12a8385d9d79263257e to your computer and use it in GitHub Desktop.

Select an option

Save charlieroberts/5708d78a3c31f12a8385d9d79263257e to your computer and use it in GitHub Desktop.
Notes for lecture 10: Scope, Module Pattern, and the Singleton Pattern

Start of class:

  • Quiz #4

Design Patterns

Module Pattern

  • Goals:
    • Encapsulate data... no polluting of namespaces
    • Control read / write access to data via closures and dedicated functions
var Module = function( arg1, arg2 ) {
  var data1 = arg1,
      data2 = arg2
      
  var instance = {
    getData1: function()  { return data1 },
    setData1: function(v) { data1 = v },
    getData2: function()  { return data2 },
    setData2: function(v) { data2 = v },    
  }
  
  return instance
}

var myinstance = Module( 1,2 )
console.log( myinstance.data1 ) // undefined
console.log( myinstance.getData1() ) // 1

Singleton Pattern

  • Goals:
    • Instantiate an object only once, usually after some type of initialization condition has been met, perhaps in a window.onload callback function.
    • Always return the same object instance.
var Singleton = function() {
  var obj = null
  
  var init = function() {
    if( obj === null ) {
      obj = {
        foo: Math.random()
      }
    }
    
    return obj
  }
  
  return init
}

var constructor = Singleton()
var singleton1 = constructor()
var singleton2 = constructor()

console.log( singleton1.foo === singleton2.foo )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment