Wednesday, April 28, 2010

US Cities Autocomplete using jQuery plugin

Simple, quick demo for us city autocomplete:

There are a lot of examples online, but sometimes they are not what you are looking for:

Here is another example using javascript arrays to do autocomplete. Each state is javascript file and contains an array of city list for that specific state.




(US Cities autocomplete), jQuery autocomplete plugin has similar demo, but as a single file, different format, check out this demo:
Check US cities autocomplete

Please note that the cities(javascript files for each state) are for demo use only, for any commercial use, please contact:
http://www.maxmind.com/


The JavaScript files for each state do not come like this, I manually extracted this info(city names for each state) from their cvs file and formatted it into an javascript array.


Official places for docs, downloads, demos, and etc.:
They provide with very nice demos and different solutions.

Plugins web site:
Authors demo page and more

jQuery web site:
jQuery plugin autocomplete

Tuesday, April 27, 2010

Case Study - Drawing - Inheritance (extract from Object Oriented JavaScript)

Case Study: Drawing Shapes

Let's finish off this chapter with a more practical example of using inheritance (check demo).

The task is to be able to calculate the area and the perimeter of different shapes, as well as to draw them, while reusing as much code as possible.

Explanation:
Let's have one Shape constructor that contains all of the common parts. From there, we can have Triangle, Rectangle and Square constructors, all inheriting from Shape. A square is really a rectangle with same-length sides, so let's reuse Rectangle when building the Square.

In order to define a shape, we'll use points with x and y coordinates.

A generic shape can have any number of points. A triangle is defined with three points, a rectangle (to keep it simpler)—with one point and the lengths of the sides.

The perimeter of any shape is the sum of its sides' lengths.

The area is shape-specific and will be implemented by each shape.
The common functionality in Shape would be:

A draw() method that can draw any shape given the points
A getParameter() method
A property that contains an array of points

Other methods and properties as needed

Let's have two other helper constructors: Point and Line.

- Point will help when defining shapes;
- Line will ease some calculations, as it can give the length of the line connecting any two given points. (using the Pythagorean Theorem: a2 + b2 = c2 (imagine a right -angled triangle where the hypotenuse connects the two given points)).


The example is very well explained in the book (Object Oriented JavaScript), so there is no point to go line by line here.

There are couple of interesting points:

1)
The last child constructor is Square. A square is a special case of a rectangle,
so it makes sense to reuse Rectangle. The easiest thing to do here is to borrow
the constructor.

  function Square(p, side){
      Rectangle.call(this, p, side, side);
  }

2)
Now that we have all constructors, let's take care of inheritance. Any pseudo-classical pattern (one that works with constructors as opposed to objects) will do.

Let's try using a modified and simplified version of the prototype-chaining pattern (the first method described in this chapter).

This pattern calls for creating a new instance of the parent and setting it as the child's prototype.

In this case, it's not necessary to have a new instance for each child—they can all share it.

   (function () {
 
      var s = new Shape();
  
      Triangle.prototype = s;
 
      Rectangle.prototype = s;
 
      Square.prototype = s;
    })();


3)
When something is written nicely like this, it very easy to add functionality. It took me couple of minutes to add fill color methods for the shapes. (CSS - webkit animation - Safari)

Here is demo.


Too many javascript code are tangled, unreadable, you can really forget about reusing it.

Here is code, also you can see it under source on demo:

 
 function Point(x, y) {
  this.x = x;
  this.y = y;
 }
 
 function Line(p1, p2) {
  this.p1 = p1;
  this.p2 = p2;
  this.length = Math.sqrt(Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2));
 }
 
 function Shape() {
  this.points = [];
  this.lines = [];
  this.init();
 }
 
 Shape.prototype = {
 //reset pointer to constructor
 constructor: Shape,
 //initialization, sets this.context to point
 //to the context of the canvas object
 init: function() {
  if(typeof this.context === 'undefined') {
   var canvas = document.getElementById('canvas');
   Shape.prototype.context = canvas.getContext('2d');
  }
 },
 //method that draws a shape by looping through this.points
 draw: function() {
  var ctx = this.context;
  ctx.strokeStyle = this.getColor();
  ctx.beginPath();
  ctx.moveTo(this.points[0].x, this.points[0].y);
  for(var i = 1; i < this.points.length; i++) {
   ctx.lineTo(this.points[i].x, this.points[i].y);
  }
  ctx.closePath();
  ctx.stroke();
 },
 //method that generates a random color
 getColor: function() {
  var rgb = [];
  for(var i = 0; i < 3; i++) {
   rgb[i] = Math.round(255 * Math.random());
  } 
  return 'rgb(' + rgb.join(',') + ')';
 },
 setFillColor: function(colorArray) {
  var ctx_f = this.context;
  var colorArray = colorArray || [100, 100, 100]; //providing default if called without color
  var rgb = [];
  for(var i =0; i < colorArray.length; i++) {
   rgb[i] = colorArray[i];
  }
  ctx_f.fillStyle = 'rgb(' + rgb.join(',') + ')';
  ctx_f.fill();
 },
 setFillAlphaColor: function(colorArray) {
  var ctx_f = this.context;
  var colorArray = colorArray || [100, 100, 100, 0.5]; //providing default if called without color
  var rgb = [];
  for(var i =0; i < colorArray.length; i++) {
   rgb[i] = colorArray[i];
  }
  ctx_f.fillStyle = 'rgba(' + rgb.join(',') + ')';
  ctx_f.fill();
 },
 //method that loops through the points array, 
 //creates Line instances and adds them to this.lines
 getLines: function() {
  if(this.lines.length > 0) {
   return this.lines;
  }
  var lines = [];
  for(var i = 0; i < this.points.length; i++) {
   lines[i] = new Line(this.points[i], (this.points[i+1]) ? this.points[i+1] : this.points[0]);
  }
  this.lines = lines;
  return lines;
 },
 //shell method, to be implemented by children
 getArea: function() {},
  //sum the lengths of all lines
 getPerimeter: function() { 
  var lines = this.getLines();
  var perim = 0;
  for(var i = 0; i < lines.length; i++) {
   perim += lines[i].length;
  }
  return perim;
 }
 
}
 
//Now the children constructors: Triangle first

function Triangle(a, b, c) {
 this.points = [a, b, c];
 this.getArea = function() {
  var p = this.getPerimeter();
  var s = p /2;
  return Math.sqrt(
   s * (s - this.lines[0].length) * (s - this.lines[1].length) * (s - this.lines[2].length)
  );
 };
}

//next comes: Rectangle constructor:

function Rectangle(p, side_a, side_b) {
 this.points = [
  p,
  new Point(p.x + side_a, p.y),  //top right
  new Point(p.x + side_a, p.y+side_b), //bottom right
  new Point(p.x, p.y + side_b) //bottom left
 ];
 this.getArea = function() { return side_a * side_b;};
} 

//last child constructor is Square: 

function Square(p, side) {
 Rectangle.call(this, p, side, side);
}


(function() {
  var s = new Shape();
  Triangle.prototype = s;
  Rectangle.prototype = s;
  Square.prototype = s; 
 
 })();


Testing part:
//Testing: 
 var p1 = new Point(100, 100);
 var p2 = new Point(300, 100);
 var p3 = new Point(200, 0);
 
//order of shapes important, so big one doesn't hide small one.  
 
//chimney  
var chim = new Rectangle(new Point(120, 40), 20, 40); 
chim.draw();
chim.getPerimeter();
chim.setFillColor([169, 27, 53]);
 
 //now you can create triangle by passing the three point to the Triangle constructor:
 //roof body
 var t = new Triangle(p1, p2 , p3);
 t.draw();
 t.getPerimeter();
 t.setFillColor([149, 38, 23]);
 
 //house body
 var hsbd = new Square(p1, 200);
 hsbd.draw();
 hsbd.setFillColor([149, 93, 23]);
 
 //door
 var r = new Rectangle(new Point(180, 200), 50, 100);
 r.draw();
 r.getArea();
 r.getPerimeter()
 r.setFillColor([110, 80, 60]);
 
 //left window
 var s = new Square(new Point(130, 130), 50);
 s.draw()
 s.getArea();
 s.getPerimeter()
 s.setFillAlphaColor([145, 190, 196, 0.7]);
 
 //right window
 var s2 = new Square(new Point(230, 130), 50);
 s2.draw()
 s2.getArea();
 s2.getPerimeter()
 s2.setFillAlphaColor([145, 190, 230, 0.4]);

Friday, April 23, 2010

Extend - Another point of view on Inheritance (Object Oriented Javascript)

Another point on Inheritance (extract from Object Oriented JavaScript book.)

The different types can roughly be divided into:
Patterns that work with constructors
Patterns that work with objects

You can also classify the patterns based on whether they:
Use the prototype
Copy properties
Do both (copy properties of the prototype)




Method Name Example Classification Notes
1
Prototype chaining
(pseudo-classical)

Child.prototype = new Parent();
     

Works with constructors
Uses the prototype chain

The default mechanism described in the ECMA standard.
Tip: move all properties/methods that are meant to be reused to the prototype, and add the non-reusable as own properties
2
Inherit only the prototype

Child.prototype = Parent.prototype;
        

Works with constructors
Copies the prototype (no prototype chain, all share the same prototype object)

More efficient since no new instances are created just for the sake of inheritance.
Prototype chain lookup during runtime is fast, since there's
no chain.
Drawback: children can modify parents' functionality
3 Temporary constructor
function extend(Child, Parent) {
   var F = function(){};
   F.prototype = Parent.prototype;
   Child.prototype = new F();
   Child.prototype.constructor = Child;
   Child.uber = Parent.prototype;
   }
   

Works with constructors
Uses the prototype chain

Unlike #1, it only inherits properties of the prototype. Own properties (created with this inside the constructor) are not inherited.
Used in YUI and Ext.js libraries
Provides convenient access to the parent (through uber) Inheritance
4
Copying the prototype properties

function extend2(Child, Parent) {
  var p = Parent.prototype;
  var c = Child.prototype;
  for (var i in p) {
  c[i] = p[i];
  } 
  c.uber = p;
   }
Works with constructors
Copies properties
Uses the prototype chain
All properties of the parent prototype become properties of the child prototype
No need to create a new object only for inheritance
Shorter prototype chains
5 Copy all properties
(shallow copy)

function extendCopy(p) {
  var c = {};
  for (var i in p) {
   c[i] = p[i];
   }
  c.uber = p; 
  return c;
  }
Works with objects
Copies properties
Very simple
Used in Firebug, earlier jQuery and Prototype.js versions
Also known as shallow copy
Doesn't use prototypes
6 Deep copy
//same as above, but recurse into objects
function deepCopy(p, c) {
    var c = c || {};
    for (var i in p) {
      if(typeof p[i] === 'object') {
        c[i] = p[i].constructor === Array) ? [] : {};
        deepCopy(p[i], c[i]);
      } else {
        c[i] = p[i];
      }
    }
    return c;
} 
    
Works with objects
Copies properties
Same as #5, but copies the objects by value
Used in more recent versions of jQuery
7 Prototypal inheritance
function object(o){ 
   function F() {};
   F.prototype = o;
    return new F();
  }
    

Works with objects
Uses the prototype chain

No pseudo-classes; objects inherit from objects
Leverages the benefits of the prototype
8 Extend and augment
function objectPlus(o, stuff) {
    var n; 
    function F() {};
    F.prototype = o;
    
    n = new F(); 
    n.uber = o;
     
    for (var i in stuff) {
     n[i] = stuff[i]; 
    }
 return n;
}
    

Works with objects
Uses the prototype chain
Copies properties

Mix of prototypal inheritance (#7) and copying properties (#5)
One function call to inherit and extend at the same time
9 Multiple inheritance
function multi() {
            var n = {}, stuff, j = 0, len = arguments.length;
             
            for (j = 0; j < len; j++) {
                stuff = arguments[j];
                    for (var i in stuff) {     
                        n[i] = stuff[i];
                    }
            }
            return n;
        }

Works with objects
Copies properties

A mixin-style implementation
Copies all the properties of all the parent objects in the order of appearance
10
Parasitic inheritance

function parasite(victim) {
  var that = object(victim);
   that.more = 1;
  return that;
 }
    
    
//example: 

var twoD = { 
    name: '2D shape',
    dimensions: 2
}

function triangle(s, h) {
    var that = parasite(twoD);
    that.name = 'Triangle';
    that.getArea = function() { return this.side * this.height / 2; };
    that.side = s;
    that.height = h;
    return that; 
}


var t = triangle(5, 10);
t.dimensions

var t2 = new triangle(5,5);
t2.getArea(); 
t2.name



    
    


Works with objects
Uses the prototype chain

Constructor-like function, creates objects
Copies an object; augments
and returns the copy
11 Borrowing constructors
function Child() {
  Parent.apply(this, arguments);
 }
Works with constructors
Inherits only own properties
Can be combined with #1 to inherit prototype too
Easy way to deal with the issues when a child inherits a property that is an object (and therefore passed by reference)
12 Borrow a constructor and copy the prototype
function Child() {
  Parent.apply(this, arguments);
 }
 extend2(Child, Parent);
    
    

Works with constructors
Uses the prototype chain
Copies properties

Combination of #11 and #4
Allows you to inherit both own properties and prototype properties without calling the parent constructor twice.


Given so many options, you are probably wondering which is the right one? That depends on your style and preferences, your project, task, and team.

Are you more comfortable thinking in terms of classes?
Then pick one of the methods that work with constructors. Are you going to need just one or a few instances of your "class"? Then choose an object-based pattern.


Are these the only ways of implementing inheritance?
No.
You can chose a pattern from the table above or you can mix them, or you can think of your own.

The important thing is to understand and be comfortable with objects, prototypes, and constructors; the rest is easy.

--end of extract from book Object Oriented JavaScript ----


It gives fresh perspective on the subject. Is it practical? No that sure, especially after you read, JavaScript Design Patterns, chapter on Inheritance. Is it helpful for better understanding, yes, still I will have to reread or revisit it from time to time.

JavaScript Design Patterns - Inheritance

(extract from JavaScript Design Patterns book)
Inheritance is a very complex topic in JavaScript, much more so than in any other objectoriented
language. Unlike most other OO languages, where a simple keyword will allow you to
inherit from a class, JavaScript requires a series of steps in order to pass on public members in
the same way.

To further complicate the issue, JavaScript is one of the few languages that uses
prototypal inheritance (we will show you how this is actually a huge benefit).

Design main goal: you want to design your classes in such a way as to reduce the amount of duplicate code and make your objects as loosely coupled as possible.

Inheritance helps with the first of those design principles, and allows you to build upon existing classes and leverage the methods they already have.


Classical Inheritance


JavaScript can be made to look like a classically inherited language. By using functions to declare classes, and the new keyword to create instances, objects can behave very similarly to objects in Java or C++.
This is a basic class declaration in JavaScript:
/* Class Person. */
function Person(name) {
this.name = name;
}
Person.prototype.getName = function() {
return this.name;
}


First create the constructor. By convention, this should be the name of the class, starting
with a capital letter.
Within the constructor, use the this keyword to create instance attributes.
To create methods, add them to the class’s prototype object, as in Person.prototype.getName.

To create an instance of this class, you need only invoke the constructor with the 'new' keyword:

var reader = new Person('John Smith');
reader.getName();
You can then access all instance attributes and call all instance methods.
This is a very simple example of a class in JavaScript.

The Prototype Chain


To create a class that inherits from Person, it gets a little more complex:

/* Class Author. */
function Author(name, books) {
Person.call(this, name); // Call the superclass's constructor in the scope of this.
this.books = books; // Add an attribute to Author.
}
Author.prototype = new Person(); // Set up the prototype chain.
Author.prototype.constructor = Author; // Set the constructor attribute to Author.
Author.prototype.getBooks = function() { // Add a method to Author.
return this.books;
};

Explanation:


First, create a constructor function, as in the previous example.
Within that constructor, call the superclass’s constructor, and pass in the name argument.
This line deserves a little more explanation. When you use the new operator, several things are done for you.

The first is that an empty object is created. The constructor
function is then called with this empty object at the front of the scope chain; the this in each constructor function refers to this empty object.

So to call the superclass’s constructor within Author, you must do the same thing manually. Person.call(this, name) will invoke the Person constructor with that empty object (which we refer to as this) at the front of the scope chain, while passing in name as an argument.

The next step is to set up the prototype chain. Despite the fact that the code used to do this
is fairly simple, it is actually a very complex topic.

As mentioned before, JavaScript has no extends keyword; instead, every object has an attribute named prototype.
This attribute points to either another object or to null. When a member of an object is accessed (as in reader.getName), JavaScript looks for this member in the prototype object if it does not exist in the current object. If it is not found there, it will continue up the chain, accessing each objects’ prototype until the member is found (or until the prototype is null).


This means that in order to make one class inherit from another, you simply need to set the subclasses’s prototype to point to an instance of the superclass. This is completely different from how inheritance works in other languages and can be very confusing and counterintuitive.


In order to have instances of Author inherit from Person, you must manually set Author’s
prototype to be an instance of Person.


The final step is to set the constructor attribute back to Author (when you set the prototype attribute to an instance of Person, the constructor attribute is wiped out).

Despite the fact that setting up this inheritance takes three extra lines, creating an instance
of this new subclass is the same as with Person:
var author = [];
author[0] = new Author('Dustin Diaz', ['JavaScript Design Patterns']);
author[1] = new Author('Ross Harmes', ['JavaScript Design Patterns']);
author[1].getName();
author[1].getBooks();

All of the complexity of classical inheritance lies within the class declaration.
Creating new instances is still simple.



The EXTEND FUNCTION

In order to make the class declaration more simple, you can wrap the whole subclassing process
in a function, called extend. It will do what the extend keyword does in other languages—create
a new object from a given class structure:
/* Extend function. */
function extend(subClass, superClass) {
var F = function() {};
F.prototype = superClass.prototype;
subClass.prototype = new F();
subClass.prototype.constructor = subClass;
}
This function does the same things that you have done manually up to this point. It sets the
prototype and then resets the correct constructor. As a bonus, it adds the empty class F into the
prototype chain in order to prevent a new (and possible large) instance of the superclass from
having to be instantiated. This is also beneficial in situations where the superclass’s constructor
has side effects or does something that is computationally intensive. Since the object that gets
instantiated for the prototype is usually just a throwaway instance, you don’t want to create it
unnecessarily.
The previous Person/Author example now looks like this:
/* Class Person. */
function Person(name) {
this.name = name;
}
Person.prototype.getName = function() {
return this.name;
}
/* Class Author. */
function Author(name, books) {
Person.call(this, name);   //superclass (Person) is hardcoded == not the best way.
this.books = books;
}
extend(Author, Person);   //EXTEND
Author.prototype.getBooks = function() {
return this.books;
};

Instead of setting the prototype and constructor attributes manually, simply call the
extend function immediately after the class declaration (and before you add any methods to
the prototype). The only problem with this is that the name of the superclass (Person) is hardcoded
within the Author declaration. It would be better to refer to it in a more general way:


/* Extend function, improved. */
function extend(subClass, superClass) {
var F = function() {};
F.prototype = superClass.prototype;
subClass.prototype = new F();
subClass.prototype.constructor = subClass;
subClass.superclass = superClass.prototype;
if(superClass.prototype.constructor == Object.prototype.constructor) {
superClass.prototype.constructor = superClass;
}
}

Download it here.
This version is a little longer but provides the superclass attribute, which you can now
use to make Author less tightly coupled to Person. The first four lines of the function are the same as before. The last three lines simply ensure that the constructor attribute is set correctly
on the superclass (even if the superclass is the Object class itself ). This will become
important when you use this new superclass attribute to call the superclass’s constructor:

/* Class Author. */
function Author(name, books) {
Author.superclass.constructor.call(this, name);  //no more hardcoded superclass's name here
this.books = books;
}
extend(Author, Person);
Author.prototype.getBooks = function() {
return this.books;
};

Adding the superclass attribute also allows you to call methods directly from the superclass.

This is useful if you want to override a method while still having access to the superclass’s implementation of it.

For instance, to override Person’s implementation of getName with a new version,
you could use Author.superclass.getName to first get the original name and then add to it:
Author.prototype.getName = function() {
var name = Author.superclass.getName.call(this);
return name + ', Author of ' + this.getBooks().join(', ');
};



Prototypal Inheritance

We’ve found the best way to think about it is to forget everything you know about classes and instances, and think only in terms of objects.
The classical approach to creating an object is to

(a) define the structure of the object, using a class declaration, and
(b) instantiate that class to create a new object.

Objects created in this manner have their own copies of all instance attributes, plus a link to the single copy of each of the instance methods.

In prototypal inheritance, instead of defining the structure through a class, you simply
create an object.

This object then gets reused by new objects, thanks to the way that prototype
chain lookups work.

It is called the prototype object because it provides a prototype for what
the other objects should look like. It is where prototypal inheritance gets its name.

We will now recreate Person and Author USING PROTOTYPAL INHERITANCE:
/* Person Prototype Object. */
var Person = {
name: 'default name',
getName: function() {
return this.name;
}
};

Instead of using a constructor function named Person to define the class structure, Person
is now an object literal. It is the prototype object for any other Person-like objects that you want
to create. Define all attributes and methods you want these objects to have, and give them
default values. For the methods, those default values will probably not be changed; for attributes,
they almost certainly will be:
var reader = clone(Person);
alert(reader.getName()); // This will output 'default name'.
reader.name = 'John Smith';
alert(reader.getName()); // This will now output 'John Smith'.

To create a new Person-like object, use the clone function (we go into more detail about
this function later in the section “The clone Function”). This provides an empty object with
the prototype attribute set to the prototype object. This means that if any method or attribute
lookup on this object fails, that lookup will instead look to the prototype object.
To create Author, you don’t make a subclass of Person. Instead you make a clone:

/* Author Prototype Object. */
var Author = clone(Person);
Author.books = []; // Default value.
Author.getBooks = function() {
return this.books;
}
The methods and attributes of this clone can then be overridden. You can change the
default values given by Person, or you can add new attributes and methods. That creates a new
prototype object, which you can then clone to create new Author-like objects:
var author = [];
author[0] = clone(Author);
author[0].name = 'Dustin Diaz';
author[0].books = ['JavaScript Design Patterns'];
author[1] = clone(Author);
author[1].name = 'Ross Harmes';
author[1].books = ['JavaScript Design Patterns'];
author[1].getName();
author[1].getBooks();

------

Please read more in the book:
Asymmetrical Reading and Writing of Inherited Members
Example shows why you must create new copies of data types that are passed by reference.

You must create new copies of all arrays and objects before you start changing their members.
It is very easy to forget this and modify the value of the prototype object. This should be avoided at all costs; debugging these types of errors can be very time-consuming.
In these situations, you can use the hasOwnProperty method to distinguish between inherited members and the object’s actual members.

------

Sometimes prototype objects will have child objects within them. If you want to override
a single value within that child object, you have to recreate the entire thing.
This can be done by setting the child object to be an empty object literal and then recreating it, but that would mean that the cloned object would have to know the exact structure and defaults for each child object.
In order to keep all objects as loosely coupled as possible, any complex child objects should be created using methods:
var CompoundObject = {
string1: 'default value',
childObject: {
bool: true,
num: 10
}
}

var compoundObjectClone = clone(CompoundObject);
// Bad! Changes the value of CompoundObject.childObject.num.
compoundObjectClone.childObject.num = 5;

// Better. Creates a new object, but compoundObject must know the structure
// of that object, and the defaults. This makes CompoundObject and
// compoundObjectClone tightly coupled.
compoundObjectClone.childObject = {
bool: true,
num: 5
};
In this example, childObject is recreated and compoundObjectClone.childObject.num is
modified. The problem is that compoundObjectClone must know that childObject has two
attributes, with values true and 10. A better approach is to have a factory method that creates
the childObject:
// Best approach. Uses a method to create a new object, with the same structure and
// defaults as the original.
var CompoundObject = {};
CompoundObject.string1 = 'default value',
CompoundObject.createChildObject = function() {
return {
bool: true,
num: 10
}
};
CompoundObject.childObject = CompoundObject.createChildObject();
var compoundObjectClone = clone(CompoundObject);
compoundObjectClone.childObject = CompoundObject.createChildObject();
compoundObjectClone.childObject.num = 5;

Comparing Classical and Prototypal Inheritance

The classical and prototypal paradigms for creating new objects are very different from each
other, and the objects that each one produces behave differently. Each paradigm has its own
pros and cons, which should help you determine which one to use in a given situation.

Classical inheritance is well understood, both in JavaScript and the programmer community
in general. Almost all object-oriented code written in JavaScript uses this paradigm. If you
are creating an API for widespread use, or if there is the possibility that other programmers not familiar with prototypal inheritance will be working on your code, it is best to go with classical.

JavaScript is the only popular, widely used language that uses prototypal inheritance, so odds
are most people will never have used it before. It can also be confusing to have an object with
links back to its prototype object.

Programmers who don’t fully understand prototypal inheritance will think of this as some sort of reverse inheritance, where the parent inherits from its children. Even though this isn’t the case, it can still be a very confusing topic.


But since this form of classical inheritance is only imitating true class-based inheritance, advanced JavaScript programmers need to understand how prototypal inheritance truly works at some point anyway.


Some would argue that hiding this fact does more harm than good.

Prototypal inheritance is very memory-efficient.



Because of the way prototype chain reads members, all cloned objects share a single copy of each attribute and method, until those attributes and methods are written to directly on the cloned object.


Contrast this with the objects created using classical inheritance, where each object has a copy of every attribute (and private method) in memory.


The savings here are enormous. It also seems to be a much more
elegant approach, needing only a single clone function, rather than several lines of incomprehensible syntax such as
SuperClass.call(this, arg)
and
SubClass.prototype = new SuperClass
for each class you want to extend (it is true, however, that some of these lines can, in turn, be condensed into the extend function).

Don’t think that just because prototypal inheritance is simple that it isn’t also complex.

Its power lies in its simplicity.

The decision to use classical or prototypal inheritance probably depends most on how well
you like each paradigm.

Some people seem naturally drawn to the simplicity of prototypal inheritance, while others are much more comfortable in the more familiar classical.

Both paradigms can be used for each pattern described in this book.

We tend toward classical inheritance for the later patterns, to make them easier to understand, but both can be used interchangeably throughout the book (Javascript Design Patterns).

I put them into seperate pages for easier reading and less clutter to this page.
Examples:

Using Classical Inheritance
Using Strict Inheritance (Extend function), please check EXTEND EXAMPLEs from Object Oriented JavaScript book.
Using Prototypal Inheritance
Using Mixin Classes Inheritance (Augment function)



When Should Inheritance Be Used?
Inheritance adds some complexity to your code and makes it harder for JavaScript novices to
understand what it does, so it should only be used in situations where its benefits outweigh
these drawbacks.
Most of the benefits have to do with code reuse. By having classes or objects
inherit from each other, you only have to define a given method once.
By the same token, if you ever have to make changes to this method or track down errors in it, the fact that it is defined in a single location can save you a great deal of time and effort.

Each paradigm also has its own pros and cons. Prototypal inheritance (with the clone function)
is best used in situations where memory efficiency is important.

Classical inheritance (with the extend function) is best used when the programmers dealing with the objects are familiar with how inheritance works in other object-oriented languages.

Both of these methods are well suited to class hierarchies where the differences between each class are slight.

If the classes are very different from each other, it usually makes more sense to augment them with methods from
mixin classes.

You will find that simpler JavaScript programs rarely require this level of abstraction.

It is only with large projects, with multiple programmers involved, that this sort of organization becomes necessary.

Inheritance - Example Mixin Classes (augment function)

Using Mixin Classes

--------
Augment Function so you can follow

/* Augment function, improved. */

function augment(receivingClass, givingClass) {
 if(arguments[2]) { // Only give certain methods.
  for(var i = 2, len = arguments.length; i < len; i++) {
   receivingClass.prototype[arguments[i]] = givingClass.prototype[arguments[i]];
  }
 } else { // Give all methods.
  for(methodName in givingClass.prototype) {
   if(!receivingClass.prototype[methodName]) {
    receivingClass.prototype[methodName] = givingClass.prototype[methodName];
   }
  }
 }
}

You can now write augment(Author, Mixin, 'serialize'); to only augment Author with the single serialize method. More method names can be added if you want to augment with more than one method. Often it makes more sense to augment a class with a few methods than it does to make one class inherit from another. This is a lightweight way to prevent code duplication. Unfortunately, there aren’t many situations where it can be used. Only methods general enough to be used in very dissimilar classes make good candidates for sharing (if the classes aren’t that dissimilar, normal inheritance is often a better choice). …end of augment part…… ------- We will repeat the example one more time using mixin classes. We will create one mixin class with all of the methods we want to share. Then we will create a new class and use augment to share those methods:
/* Mixin class for the edit-in-place methods. */


var EditInPlaceMixin = function() {};  //empty Constructor

EditInPlaceMixin.prototype = {
 createElements: function(id) {
  this.containerElement = document.createElement('div');
  this.parentElement.appendChild(this.containerElement);
  
  this.staticElement = document.createElement('span');
  this.containerElement.appendChild(this.staticElement);
  this.staticElement.innerHTML = this.value;
  
  this.fieldElement = document.createElement('input');
  this.fieldElement.type = 'text';
  this.fieldElement.value = this.value;
  this.containerElement.appendChild(this.fieldElement);
  
  this.saveButton = document.createElement('input');
  this.saveButton.type = 'button';
  this.saveButton.value = 'Save';
  this.containerElement.appendChild(this.saveButton);
  
  this.cancelButton = document.createElement('input');
  this.cancelButton.type = 'button';
  this.cancelButton.value = 'Cancel';
  this.containerElement.appendChild(this.cancelButton);
  
  this.convertToText();
 },
 attachEvents: function() {
  var that = this;
  addEvent(this.staticElement, 'click', function() { that.convertToEditable(); });
  addEvent(this.saveButton, 'click', function() { that.save(); });
  addEvent(this.cancelButton, 'click', function() { that.cancel(); });
 },
 convertToEditable: function() {
  this.staticElement.style.display = 'none';
  this.fieldElement.style.display = 'inline';
  this.saveButton.style.display = 'inline';
  this.cancelButton.style.display = 'inline';
  
  this.setValue(this.value);
 },
 save: function() {
  this.value = this.getValue();
  var that = this;
  var callback = {
   success: function() { that.convertToText(); },
   failure: function() { alert('Error saving value.'); }
  };
  ajaxRequest('GET', 'save.php?id=' + this.id + '&value=' + this.value, callback);
 },
 cancel: function() {
  this.convertToText();
 },
 convertToText: function() {
  this.fieldElement.style.display = 'none';
  this.saveButton.style.display = 'none';
  this.cancelButton.style.display = 'none';
  this.staticElement.style.display = 'inline';
  this.setValue(this.value);
 },
 setValue: function(value) {
  this.fieldElement.value = value;
  this.staticElement.innerHTML = value;
 },
 getValue: function() {
  return this.fieldElement.value;
 }
};


The mixin class holds nothing but the methods. To create a functional class, make a constructor and then call augment:
/* EditInPlaceField class. */
function EditInPlaceField(id, parent, value) {
   this.id = id;
   this.value = value || 'default value';
   this.parentElement = parent;
   this.createElements(this.id);
   this.attachEvents();
};

augment(EditInPlaceField, EditInPlaceMixin);     //AUGMENT CALL

You can now instantiate the class in the exact same way as with classical inheritance. To create the class that uses a text area field, you will not subclass EditInPlaceField. Instead, simply create a new class (with a constructor) and augment it from the same mixin class. But before augmenting it, define a few methods. Since these are in place before augmenting it, they will not get overridden:
/* EditInPlaceArea class. */


function EditInPlaceArea(id, parent, value) {
 this.id = id;
 this.value = value || 'default value';
 this.parentElement = parent;
 this.createElements(this.id);
 this.attachEvents();
};

// Add certain methods so that augment won't include them.
EditInPlaceArea.prototype.createElements = function(id) {
 this.containerElement = document.createElement('div');
 this.parentElement.appendChild(this.containerElement);
 
 this.staticElement = document.createElement('p');
 this.containerElement.appendChild(this.staticElement);
 this.staticElement.innerHTML = this.value;
 
 this.fieldElement = document.createElement('textarea');
 this.fieldElement.value = this.value;
 this.containerElement.appendChild(this.fieldElement);
 
 this.saveButton = document.createElement('input');
 this.saveButton.type = 'button';
 this.saveButton.value = 'Save';
 this.containerElement.appendChild(this.saveButton);
 
 this.cancelButton = document.createElement('input');
 this.cancelButton.type = 'button';
 this.cancelButton.value = 'Cancel';
 this.containerElement.appendChild(this.cancelButton);
 
 this.convertToText();
};

EditInPlaceArea.prototype.convertToEditable = function() {
 this.staticElement.style.display = 'none';
 this.fieldElement.style.display = 'block';
 this.saveButton.style.display = 'inline';
 this.cancelButton.style.display = 'inline';
 
 this.setValue(this.value);
};

EditInPlaceArea.prototype.convertToText = function() {
 this.fieldElement.style.display = 'none';
 this.saveButton.style.display = 'none';
 this.cancelButton.style.display = 'none';
 this.staticElement.style.display = 'block';
 
 this.setValue(this.value);
};

augment(EditInPlaceArea, EditInPlaceMixin);   //AUGMENT CALL



The mixin technique works in this example, but not as well as the other two techniques.
In the end, the objects created by each of the techniques are almost identical, but from an
organizational standpoint, strict inheritance makes more sense than augmentation.

Mixin classes work well for methods that are shared between several disparate classes, but in this example, the mixin class is used to provide all of the methods, for two very similar classes.

Code maintenance would be easier with the first two examples because it is immediately obvious
where the methods came from and how the classes and objects were organized.

Sharing general-purpose methods that can act on all types of objects is a much better use
of mixin classes. Some examples of this are methods that serialize an object to a string representation, or output its state for debugging.

It is also possible to use mixin classes to emulate
enumerations or iterators, as found in some other object-oriented languages.

Inheritance - Example - Prototypal Inheritance

Using Prototypal Inheritance

Despite the fact that classical and prototypal inheritance are fundamentally different, repeating the exercise using prototypal inheritance really shows how similar the end code can be
between the two:

/* EditInPlaceField object. */

var EditInPlaceField = {
 configure: function(id, parent, value) {
  this.id = id;
  this.value = value || 'default value';
  this.parentElement = parent;
  this.createElements(this.id);
  this.attachEvents();
 },
 createElements: function(id) {
  this.containerElement = document.createElement('div');
  this.parentElement.appendChild(this.containerElement);
  
  this.staticElement = document.createElement('span');
  this.containerElement.appendChild(this.staticElement);
  this.staticElement.innerHTML = this.value;
  
  this.fieldElement = document.createElement('input');
  this.fieldElement.type = 'text';
  this.fieldElement.value = this.value;
  this.containerElement.appendChild(this.fieldElement);
  
  this.saveButton = document.createElement('input');
  this.saveButton.type = 'button';
  this.saveButton.value = 'Save';
  this.containerElement.appendChild(this.saveButton);
  
  this.cancelButton = document.createElement('input');
  this.cancelButton.type = 'button';
  this.cancelButton.value = 'Cancel';
  this.containerElement.appendChild(this.cancelButton);
  
  this.convertToText();
 },
 attachEvents: function() {
  var that = this;
  addEvent(this.staticElement, 'click', function() { that.convertToEditable(); });
  addEvent(this.saveButton, 'click', function() { that.save(); });
  addEvent(this.cancelButton, 'click', function() { that.cancel(); });
 },
 convertToEditable: function() {
  this.staticElement.style.display = 'none';
  this.fieldElement.style.display = 'inline';
  this.saveButton.style.display = 'inline';
  this.cancelButton.style.display = 'inline';
  this.setValue(this.value);
 },
 save: function() {
  this.value = this.getValue();
  var that = this;
  var callback = {
   success: function() { that.convertToText(); },
   failure: function() { alert('Error saving value.'); }
   };
  ajaxRequest('GET', 'save.php?id=' + this.id + '&value=' + this.value, callback);
 },
 cancel: function() {
  this.convertToText();
 },
 convertToText: function() {
  this.fieldElement.style.display = 'none';
  this.saveButton.style.display = 'none';
  this.cancelButton.style.display = 'none';
  this.staticElement.style.display = 'inline';
  this.setValue(this.value);
 },
 setValue: function(value) {
  this.fieldElement.value = value;
  this.staticElement.innerHTML = value;
 },
 getValue: function() {
  return this.fieldElement.value;
 }
};


Instead of a class, there is now an object.
Prototypal inheritance doesn’t use constructors,
so you move that code into a configure method instead. Other than that, the code is almost
identical to the first example.

Creating new objects from this EditInPlaceField prototype object looks very different from instantiating a class:
var titlePrototypal = clone(EditInPlaceField);
titlePrototypal.configure(' titlePrototypal ', $('doc'), 'Title Here');
var currentTitleText = titlePrototypal.getValue();

Instead of using the new operator, use the clone function to create a copy.
Then configure that copy.
At this point you can interact with the object titlePrototypal in the same way as
you would with the previous titleClassical object.
The two objects are almost indistinguishable and can be managed using the same API.

Creating a child object from this one also uses the clone function:
/* EditInPlaceArea object. */


var EditInPlaceArea = clone(EditInPlaceField);


// Override certain methods.
EditInPlaceArea.createElements = function(id) {
 this.containerElement = document.createElement('div');
 this.parentElement.appendChild(this.containerElement);
 
 this.staticElement = document.createElement('p');
 this.containerElement.appendChild(this.staticElement);
 this.staticElement.innerHTML = this.value;
 
 this.fieldElement = document.createElement('textarea');
 this.fieldElement.value = this.value;
 this.containerElement.appendChild(this.fieldElement);
 
 this.saveButton = document.createElement('input');
 this.saveButton.type = 'button';
 this.saveButton.value = 'Save';
 this.containerElement.appendChild(this.saveButton);
 
 this.cancelButton = document.createElement('input');
 this.cancelButton.type = 'button';
 this.cancelButton.value = 'Cancel';
 this.containerElement.appendChild(this.cancelButton);
 
 this.convertToText();
};

EditInPlaceArea.convertToEditable = function() {
 this.staticElement.style.display = 'none';
 this.fieldElement.style.display = 'block';
 this.saveButton.style.display = 'inline';
 this.cancelButton.style.display = 'inline';
 
 this.setValue(this.value);
};
EditInPlaceArea.convertToText = function() {
 this.fieldElement.style.display = 'none';
 this.saveButton.style.display = 'none';
 this.cancelButton.style.display = 'none';
 this.staticElement.style.display = 'block';
 
 this.setValue(this.value);
};



You simply create a copy of the EditInPlaceField object, and then overwrite some of the
methods.
This prototype object can be used and cloned in the same way as the first one can.
In fact, new prototype objects can be created in the same way, by cloning this one and making
a few changes.
Prototypal inheritance also seems ideal for this example, for the same reasons that classical
inheritance worked so well.
The only differences between the two are the way the class/object
is set up, and the way a new sub-object/instance is created.

Most of the code (including all of the methods) is completely unchanged. This illustrates how easily you can convert from one
paradigm to the other.

It isn’t always this easy, especially with classes and objects that make
extensive use of arrays or objects as members, but for the most part you need only modify
a bit of the syntax.

Using prototypal inheritance in this example doesn’t really provide anything over classical
inheritance.
The objects do not use many default values, so you aren’t really saving any memory.

Personally, we would have a hard time picking one paradigm over the other in this example;
both work equally well.

Inheritance (JSDP) - Example - Strict Inheritance

Here is the extend function in order to use the example bellow.
function extend(subClass, superClass) {
 var F = function() {};
 F.prototype = superClass.prototype;
 subClass.prototype = new F();
 subClass.prototype.constructor = subClass;
 
 subClass.superClass = superClass.prototype;
 
 if(superClass.prototype.constructor == Object.prototype.constructor) {
  superClass.prototype.constructor = superClass;
 }
 
}

Also please check the Extend blog from Object Oriented JavaScript, it shows different flavors of extend (copy). It's nice to see different input/explanation.


It continues on previous example EditInPlaceField class.

Next, create a class that will use a TEXT AREA instead of a TEXT INPUT. For the most part the
EditInPlaceField and EditInPlaceArea classes are identical, so create one as a subclass of
the other in order to prevent code duplication:

/* EditInPlaceArea class. */

function EditInPlaceArea(id, parent, value) {
  EditInPlaceArea.superclass.constructor.call(this, id, parent, value);
};

extend(EditInPlaceArea, EditInPlaceField);    //extending EditInPlaceField

// Override certain methods.
EditInPlaceArea.prototype.createElements = function(id) {
 this.containerElement = document.createElement('div');
 this.parentElement.appendChild(this.containerElement);
 this.staticElement = document.createElement('p');
 this.containerElement.appendChild(this.staticElement);
 this.staticElement.innerHTML = this.value;
 this.fieldElement = document.createElement('textarea');
 this.fieldElement.value = this.value;
 this.containerElement.appendChild(this.fieldElement);
 this.saveButton = document.createElement('input');
 this.saveButton.type = 'button';
 this.saveButton.value = 'Save';
 this.containerElement.appendChild(this.saveButton);
 this.cancelButton = document.createElement('input');
 this.cancelButton.type = 'button';
 this.cancelButton.value = 'Cancel';
 this.containerElement.appendChild(this.cancelButton);
 this.convertToText();
};

EditInPlaceArea.prototype.convertToEditable = function() {
 this.staticElement.style.display = 'none';
 this.fieldElement.style.display = 'block';
 this.saveButton.style.display = 'inline';
 this.cancelButton.style.display = 'inline';
 this.setValue(this.value);
};

EditInPlaceArea.prototype.convertToText = function() {
 this.fieldElement.style.display = 'none';
 this.saveButton.style.display = 'none';
 this.cancelButton.style.display = 'none';
 this.staticElement.style.display = 'block';
 this.setValue(this.value);
};

You create the subclass using the extend function and then override a few methods to
implement the changes. This new class uses a text area instead of a text input, and a paragraph
tag instead of a span.
Classical inheritance seems like an ideal technique to use in this case. Subclassing the
EditInPlaceField class is trivial, requiring only a few lines of code. Making changes to the class
is as simple as overriding or adding methods on the prototype. We could link the field to another
output by creating another subclass and overriding the save method. Since the changes between
classes are small, strict inheritance like this is ideal.

Inheritance (JSDP) - Example - Classical Inheritance

Using Classical Inheritance

First we will create an API using classical inheritance:

/* EditInPlaceField class. */

function EditInPlaceField(id, parent, value) {
 this.id = id;
 this.value = value || 'default value';
 this.parentElement = parent;
 this.createElements(this.id);
 this.attachEvents();
};


EditInPlaceField.prototype = {
  createElements: function(id) {
     this.containerElement = document.createElement('div');
     this.parentElement.appendChild(this.containerElement);
   
     this.staticElement = document.createElement('span');
     this.containerElement.appendChild(this.staticElement);
     this.staticElement.innerHTML = this.value;
   
     this.fieldElement = document.createElement('input');
     this.fieldElement.type = 'text';
     this.fieldElement.value = this.value;
     this.containerElement.appendChild(this.fieldElement);
   
     this.saveButton = document.createElement('input');
     this.saveButton.type = 'button';
     this.saveButton.value = 'Save';
     this.containerElement.appendChild(this.saveButton);

     this.cancelButton = document.createElement('input');
     this.cancelButton.type = 'button';
     this.cancelButton.value = 'Cancel';
     this.containerElement.appendChild(this.cancelButton);

     this.convertToText();
  },
  attachEvents: function() {
     var that = this;
     addEvent(this.staticElement, 'click', function() { that.convertToEditable(); });
     addEvent(this.saveButton, 'click', function() { that.save(); });
     addEvent(this.cancelButton, 'click', function() { that.cancel(); });
  },
  convertToEditable: function() {
     this.staticElement.style.display = 'none';
     this.fieldElement.style.display = 'inline';
     this.saveButton.style.display = 'inline';
     this.cancelButton.style.display = 'inline';
     this.setValue(this.value);
  },
  save: function() {
     this.value = this.getValue();
     var that = this;
     var callback = {
        success: function() { that.convertToText(); },
        failure: function() { alert('Error saving value.'); }
      };
      ajaxRequest('GET', 'save.php?id=' + this.id + '&value=' + this.value, callback);
  },
  cancel: function() {
      this.convertToText();
  },
  convertToText: function() {
     this.fieldElement.style.display = 'none';
     this.saveButton.style.display = 'none';
     this.cancelButton.style.display = 'none';
     this.staticElement.style.display = 'inline';
     this.setValue(this.value);
  },
  setValue: function(value) {
     this.fieldElement.value = value;
     this.staticElement.innerHTML = value;
  },
  getValue: function() {
     return this.fieldElement.value;
  }
};


To create a field, instantiate the class:
  var titleClassical = new EditInPlaceField('titleClassical', $('doc'), 'Title Here');
  var currentTitleText = titleClassical.getValue();

This gives an instance of the EditInPlaceField class (which will be subclassed later), with
the text displayed in a span tag and a text input field used as the editing area. It has a couple of configuration methods (createElements, attachEvents), a few internal methods for converting
and saving (convertToEditable, save, cancel, convertToText), and an accessor and mutator
pair (getValue, setvalue). If this were to be used as production code, it would be a good idea
to give each of the HTML elements specific class names so that they can be styled with CSS;
for the sake of simplicity, we don’t include these lines of code.

Monday, April 19, 2010

JavaScript Closures

1) An Example of closure and scope (extract from JavaScript Design Patterns):

In this example, a is defined in the function 'outerFunc', but the function 'innerFunc' can access it because
'innerFunc' is also defined within 'outerFunc'.


function outerFunc() {
  var a = 10;
 
 function innerFunc() {
  a *=2;
  return a;
 }
 return innerFunc;
 }

 
 var newF = outerFunc();  //newF is now a reference to function 'innerFunc'.
newF(); //returns 20.
newF(); //returns 40.
newF(); //returns 80.

var difF = outerFunc(); // difF is another reference to 'innerFunc'.
difF(); //returns 20, because a new copy of a is being used.

Here 'a' reference to the function 'innerFunc' is returned and assigned to the variable 'newF'. This
function is now executed outside of 'outerFunc', and it still has access to 'a'.
This is possible because JavaScript is lexically scoped.
Functions run in the scope they are defined in (in this case, the
scope within 'outerFunc'), rather than the scope they are executed in. As long as 'innerFunc' is defined within
'outerFunc', it has access to all of outerFunc’s variables, even if 'outerFunc' is finished executing.
This is an example of a CLOSURE.


The most common way of creating a closure is by returning a nested function.


2) Closure (extract from JavaScript Good Parts)

We will initialize myObject by calling a function that returns an object literal. That function defines a value variable. That variable is always available to the increment and getValue methods, but the function's scope keeps it hidden from the rest of the program:
var myObject = function (  ) {
    var value = 0;

    return {
        increment: function (inc) {
            value += typeof inc === 'number' ? inc : 1;
        },
        getValue: function (  ) {
            return value;
        }
    }
}(  );


We are not assigning a function to myObject. We are assigning the result of invoking that function. Notice the ( ) on the last line. The function returns an object containing two methods, and those methods continue to enjoy the privilege of access to the value variable.



3) Closure (extract from JavaScript Good Parts)



It is important to understand that the inner function has access to the actual variables of the outer functions and not copies in order to avoid the following problem:

Code View:
// BAD EXAMPLE

// Make a function that assigns event handler functions to an array
of nodes the wrong way.
// When you click on a node, an alert box is supposed to display the ordinal
of the node.
// But it always displays the number of nodes instead.
var add_the_handlers = function (nodes) {
    var i;
    for (i = 0; i < nodes.length; i += 1) {
        nodes[i].onclick = function (e) {
            alert(i);
        }
    }
};
// END BAD EXAMPLE
The add_the_handlers function was intended to give each handler a unique number (i). It fails because the handler functions are bound to the variable i, not the value of the variable i at the time the function was made:
Code View:
// BETTER EXAMPLE
// Make a function that assigns event handler functions to an array of nodes the right way. // When you click on a node, an alert box will display the ordinal of the node.
var add_the_handlers = function (nodes) {
    var i;
    for (i = 0; i < nodes.length; i += 1) {
        nodes[i].onclick = function (i) {
            return function (e) {
                alert(i);
            };
        }(i);
    }
};
Now, instead of assigning a function to onclick, we define a function and immediately invoke it, passing in i. That function will return an event handler function that is bound to the value of i that was passed in, not to the i defined in add_the_handlers. That returned function is assigned to onclick.
Note: I saw this example in real life project, so it's not something, like it only happens in theory.

4) Closure (extract from Object Oriented JavaScript)

When you pass an argument to a function it becomes available as a local variable. You can create a function that returns another function, which in turn returns its parent's argument.
function f(arg) { 
 var n = function(){
   return arg;
 };
 arg++; 
 return n;
}
You use the function like this:
var m = f(123); 
m();
//result: 124
Notice how arg++ was incremented after the function was defined and yet, when called, m() returned the updated value. This demonstrates how the function binds to its scope, not to the current variables and their values found in the scope.

5) Closures in a Loop (extract from Object Oriented JavaScript)

Here's something that can easily lead to hard-to-spot bugs, because, on the surface, everything looks normal. Let's loop three times, each time creating a new function that returns the loop sequence number. The new functions will be added to an array and we'll return the array at the end. Here's the function:
ffunction f() {
  var a = [];
  var i;
  for(i = 0; i < 3; i++) {
    a[i] = function() {
        return i;
     }
    }
   return a;
}

Let's run the function, assigning the result to the array a.
 var a = f();

a[0]() //returns: 3

a[1]() //returns: 3

a[2]()  //returns: 3
Now you have an array of three functions. Let's invoke them by adding parentheses after each array element. The expected behavior is to see the loop sequence printed out: 0, 1, and 2. Let's try: >>> a[0]() 3 >>> a[1]() 3 >>> a[2]() 3 Hmm, not quite what we expected. What happened here? We created three closures that all point to the same local variable i. Closures don't remember the value, they only link (reference) the i variable and will return its current value. After the loop, i's value is 3. So all the three functions point to the same value. (Why 3 and not 2 is another good question to think about, for better understanding the for loop.)
So how do you implement the correct behavior? You need three different variables.
An elegant solution is to use another closure:
function f() {
    var a = [];
    var i;
    for(i=0; i< 3; i++) {
        a[i] = (function(x) {
            return function() {
            return x;
            }
          })(i);
     }
    return a;
}
Usage/Test Result:
var ba = f();
ba[0]();
ba[1]();
ba[2]();

Here, instead of just creating a function that returns i, you pass i to another self-executing function. For this function, i becomes the local value x, and x has a different value every time.

Alternatively, you can use a "normal" (as opposed to self-invoking) inner function to achieve the same result. The key is to use the middle function to "localize" the value of i at every iteration.

function f() {
    function makeClosure(x) {
        return function() {
            return x;
        }
    }
    var a = [];
    var i;
    for(i = 0; i < 3; i++) {
        a[i] = makeClosure(i);
    }
    return a;
}
var bc = f();
bc[0]();
bc[1]();
bc[2]();

6) Closure - Getter/Setter (extract from Object Oriented JavaScript)

Imagine you have a variable that will contain a very specific range of values. You don't want to expose this variable because you don't want just any part of the code to be able to alter its value.

You protect this variable inside a function and provide two additional functions—one to get the value and one to set it. The one that sets it could contain some logic to validate a value before assigning it to the protected variable (let's skip the validation part for the sake of keeping the example simple).

You place both the getter and the setter functions inside the same function that contains the secret variable, so that they share the same scope:

var getValue, setValue;
(function() {
    var secret = 0;
 getValue = function() {
    return secret;
};
setValue = function(v) {
   //should perform some validation
    secret = v;
}
})();

In this case, the function that contains everything is a self-invoking anonymous function. It defines setValue() and getValue() as global functions, while the secret variable remains local and inaccessible directly.

//getValue();
setValue(123);
getValue()

7) Closure - Iterator (extract from Object Oriented JavaScript)

You already know how to loop through a simple array, but there might be cases where you have a more complicated data structure with different rules as to what the sequence of values is.

You can wrap the complicated "who's next" logic into an easy-to-use next() function. Then you simply call next() every time you need the consecutive value. For this example, we'll just use a simple array, and not a complex data structure.

Here's an initialization function that takes an input array and also defines a private pointer i that will always point to the next element in the array.

function setup(x) {
    var i = 0;
    return function() {
        return x[i++];
    };
}

Calling the setup() function with a data array will create the next() function for you.

var next = setup (['a', 'b', 'c']);

From there it's easy and fun: calling the same function over and over again gives you the next element.

next();  //returns "a"
next();   //returns "b"
next();   //returns "c"

To Sum Up:

JavaScript offers a lot of fun with its flexibility.

JavaScript Design Patterns - Constants

Constant generic accessor method:

If you have a lot of constants and don’t want to create an accessor method for each, you
can create a single generic accessor method:


var Class = (function() {
  
 //Private static attributes.   
 var constants = {
  UPPER_BOUND: 100,
  LOWER_BOUND: -100
 };
 
 
 //Privileged static method. (keep in mind, IT'S NOT PRIVATE!!!)  
 this.getConstant = function (name) {
  return constants[name];
 }
 
 //Return the constructor.
 return function(constructorArgument) {
  
  
  
  //Private attributes.
  var isbn, title, author;
  
  //Privileged methods.
  this.getTitle = function() {
   return title;
  };
  this.setTitle = function(newTitle) {
   title = newTitle || 'No Title specified';
  };
 }
 
 
 })();

Usage: try it in Firebug
Then you would get a constant by calling the single accessor:
Author's suggestion in the book is not working, since it get's propagate the prototype chain all the way to the Object in javascript hierarchy.


Class.getConstant('UPPER_BOUND');  //(Book's example) not working it went up prototype chain to the Object
  
  getConstant('UPPER_BOUND');  //working = returns: 100
  
  //in firebug if you do somethig like this: 
  var cl = new Class ('mynewtitle');
  cl.getConstant('UPPER_BOUND'); //error not function
  
  getConstant instanceof Object; //returns true
  getConstant instanceof Function; //returns true
  getConstant instanceof Class;   //returns false
  getConstant instanceof window;  //returns false
  
 

Here, we call getConstant method as is. I don't think this is what author meant as 'Privileged static method'.

Friday, April 16, 2010

JavaScript Design Patterns - Encapsulation & Information Hiding

Despite the fact that JavaScript is an object-oriented language, it does not have any built-in mechanisms for declaring members to be public or private.

There are several established patterns for creating objects with public, private, and privileged methods, each with its own strengths and weaknesses.

Encapsulation and Information Hiding

How is encapsulation related to information hiding? You can think of it as two ways of referring to the same idea.

Information hiding is the goal, and encapsulation is the technique you use to accomplish that goal.

Encapsulation can be defined as the hiding of internal data representation and implementation details in an object. The only way to access the data within an encapsulated object is to use defined operations.

In OO Languages they use "private" keyword.
In JavaScript, we will use the concept of the closure to create methods and attributes that can be only accessed from within the object. It is more complicated (and confusing) than just using keywords, but the same end result can be achieved.

The role/importance of the Interface:

Interface provides a contract that documents the publicly accessible methods. It defines the relationship that two objects can have; either objects in this relationship can be replaced as long as the interface is maintained.

The ideal software system will define interfaces for all classes. Those classes will provide only the methods defined in their interfaces; any other method will be kept private. All attributes will be private and only accessible through accessor and mutator operations defined in the interface.

This 'interface' explanation you can find in many object oriented languages books (java, C#, ActionScript 3.0, Objective-C 2.0, etc, etc.).


Basic Patterns:

- fully exposed object is the simplest but provides only public members.
Fully Exposed Demo
- using 'underscores' to denote methods and attributes that are intended to be private.
Underscores Demo
- third, uses 'closures' to create true private members, which can only be accessed through the use of privileged methods.
Using Closures to create private memebers Demo

Wednesday, April 14, 2010

JavaScript Design Patterns - Interface

I read the book couple of times, and would like to post simple summaries on the topics that are written in the book and post some examples (add some more later). I like the book, but it's sometimes very high level descriptions of pro and cons that need more practical usage.

You can buy this book here: Pro JavaScript Design Patterns by Ross Harmes and Dustin Diaz, publisher Apess.

Let's start with Interface.

An Interface provides a way of specifying what methods an object should have.

It does not specify how those methods should be implemented.
This is typical definition for other object oriented languages (i.e. java).

Three ways of emulating interfaces in javascript:

comments

attribute checking

duck typing


The interface class:
// Constructor.
var Interface = function(name, methods) {
    if(arguments.length != 2) {
        throw new Error("Interface constructor called with " + arguments.length
          + "arguments, but expected exactly 2.");
    }
    
    this.name = name;
    this.methods = [];
    for(var i = 0, len = methods.length; i < len; i++) {
        if(typeof methods[i] !== 'string') {
            throw new Error("Interface constructor expects method names to be " 
              + "passed in as a string.");
        }
        this.methods.push(methods[i]);        
    }    
};    

// Static class method.
Interface.ensureImplements = function(object) {
    if(arguments.length < 2) {
        throw new Error("Function Interface.ensureImplements called with " + arguments.length  + "arguments, but expected at least 2.");
    }

    for(var i = 1, len = arguments.length; i < len; i++) {
  //book's example uses interface word, this is reserved word, so I changed it.
        var interFaceObjectArray = arguments[i];
        if(interFaceObjectArray.constructor !== Interface) {
            throw new Error("Function Interface.ensureImplements expects arguments "   
              + "two and above to be instances of Interface.");
        }
        
        for(var j = 0, methodsLen = interFaceObjectArray.methods.length; j < methodsLen; j++) {
            var method = interFaceObjectArray.methods[j];
            if(!object[method] || typeof object[method] !== 'function') {
                throw new Error("Function Interface.ensureImplements: object " 
                  + "does not implement the " + interFaceObjectArray.name 
                  + " interface. Method " + method + " was not found.");
            }
        }
    } 
};

Best usage for Interfaces: It becomes most beneficial when you start implementing complex systems usings design patterns. It might seem like interfaces reduce JavaScript's flexibility, but they actually improve it by allowing your objects to be more loosley coupled. Your functions can be more flexible because you can pass in arguments of any type and still ensure that only objects with the needed method will be used. Patterns That Rely on the Interface: - Factory Pattern The specific objects that are created by a factory can change depending on the situation. In order to ensure that the objects created can be used interchangeably, interfaces are used. "...This means that a factory is guaranteed to produce an object that will implement the needed methods...." (sounds like from java book.) - Composite Pattern You can't use this pattern without an interface. The most important idea behind the composite is that groups of objects can be treated the same as the constituent objects. This is accomplished by implementing the same interface. - Decorator Pattern A decorator works by transparently wrapping another object. This is accomplished by implementing the exact ame interface as the other object; from the outside, the decorator and the object it wraps look identical. We use the Interface class to ensure that any decorator objects created implement the needed methods. - Command Pattern All command objects within your code will implement the same methods (like execute, run, etc). By using interfaces, you can create classes that can execute these commands without needing to know anything about them, other than the fact that they implement the correct interface. This allows you to create extremely modular and loosely coupled user interfaces and API's. I started from the last one, I will redo this page and add more info to explain the Command Pattern and others as time permits. The goal is to bring it from theory into more everyday things. Others are using it to build complex systems already, but I feel it needs more discussion and to spread the word. Here is another quote from the book:
The first principle of reusable object-oriented design mentioned in the Gang of Four's Design Patterns says "Program to an interface, not an implementation," telling you how fundamental this concept is.
Please check out the Command Pattern demo here. Here to Download.

Thursday, April 1, 2010

Designing Web Interfaces - Some Thoughts, Examples, and So On

Designing Web Applications are becoming more and more important.

Today (04/01/2010) one of the sites is changing just one word. They are replacing word 'fan' with the word 'like'. It's very subtle change but very well thought out. It's things like this that's important to constantly read and follow the trends and changes in design and technology.


The book "Designing Web Interfaces" is good refresher for seasoned Front End Developers, Designers, Architects, and whoever likes web design/user interface.


I created a nice summary from the book, Tabbed Summary, where you can see the topics all together much easier(needs more things to be added, but when time permits, I will update the rest of pages).
(Reading the book is highly recommended!!!).

The tabbed interface code, is from another very nice resource, a UK magazine Practical Web Design, every month gets published. Barnes and Nobles and Borders stores caries the magazine.

They are out there other resources and books as well. I will try to add more as time permits.


Here is an example of Expand and Collapse that is mentioned in the book, or as Inline Assistant Process in other part of the book.


In the book they mention use of hover menu (I will correct the wording later.) and that is hard to implement. I have to agree, it's really a lot of work, with very little return for the effort.
Here is the Hover Menu