JavaScript/Notes/Singleton

From Noisebridge
< JavaScript(Difference between revisions)
Jump to: navigation, search
Line 22: Line 22:
 
<source lang="javascript">
 
<source lang="javascript">
 
// Not a Singleton.
 
// Not a Singleton.
var c = function(a) {
+
var C = function(a) {
 
   var b = a + 2;
 
   var b = a + 2;
 
   this.name = b;
 
   this.name = b;
 
};
 
};
  
var anObject = new c();
+
var anObject = new C(a);
 
</source>
 
</source>
 
Example: Constructors and prototype inheritance.
 
Example: Constructors and prototype inheritance.
Line 35: Line 35:
 
<source lang="javascript">
 
<source lang="javascript">
 
var anObject = new function(a) {
 
var anObject = new function(a) {
 +
// hidden variables.
 
   var b = a + 2;
 
   var b = a + 2;
 
   this.name = b;
 
   this.name = b;
 
}(3);
 
}(3);
 +
 +
alert(anObject.name);
 +
alert(typeof b); // "undefined"
 
</source>
 
</source>
 +
 +
The function scope allows us to hide variable `b`.
 
[http://jsbin.com/ErAHEFo/1/edit jsbin]
 
[http://jsbin.com/ErAHEFo/1/edit jsbin]
  
 +
An object literal does not allow information hiding:
 +
<source lang="javascript">
 +
// exposed variables.
 +
var a = 3;
 +
var b = a + 2;
 +
var anObject = {
 +
  name : b;
 +
};
 +
</source>
  
 
Example: [http://garretts.github.io/ape-javascript-library/build/anim/Animation.js APE Animation Manager]
 
Example: [http://garretts.github.io/ape-javascript-library/build/anim/Animation.js APE Animation Manager]

Revision as of 10:03, 23 November 2013

Singleton with information hiding.

Lazy Initialization

function getAnObject(a) {
  var anObject;
 
  var b = a + 1;
 
  return (getAnObject = function() {
    if(! anObject ) {
      anObject = {name: b};
    }
    return anObject;
  })();
}

Eager Initialization

Not a Singleton, but a constructor.

// Not a Singleton.
var C = function(a) {
  var b = a + 2;
  this.name = b;
};
 
var anObject = new C(a);

Example: Constructors and prototype inheritance. jsbin

Singleton:

var anObject = new function(a) {
// hidden variables.
  var b = a + 2;
  this.name = b;
}(3);
 
alert(anObject.name); 
alert(typeof b); // "undefined"

The function scope allows us to hide variable `b`. jsbin

An object literal does not allow information hiding:

// exposed variables.
var a = 3;
var b = a + 2;
var anObject = {
  name : b;
};

Example: APE Animation Manager

Personal tools