JavaScript Design Patterns

11:19 AM Xun 2 Comments

You may say JavaScript is at its golden age now, it reigns as the indisputable language of the web. With the demand comes the supply. Over the past 5 or 6 years, over 100 of JavaScript libraries have sprung up, some of them aiming at solutions for common tasks such as event handling, dom traversal, standard AJAX call, others intends to provide a framework upon which programmers can readily extend and deploy.


So did various design patterns in JavaScript emerge.

What are design patterns?

In JavaScript or software engineering in general, "a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design. A design pattern is not a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that can be used in many different situations. "
Software design pattern


Why design patterns in JavaScript? Well, first of all, no, you do not have to use any design patterns. However like how JavaScript libraries can make your life easier, design patterns probably can make your code cleaner and more robust especially as the application is getting more complex. JavaScript is an extremely flexible language, it is loosely-typed, its functions are first-class objects that can be created and passed around dynamically. The only scope is functional scope, anything outside of a function is global and can be accessed and modified. All of this flexibility is a double-edged sword can spell power and potential for misuse or abuse.

In the realm of software engineering, design patterns are categorized as creational, behavioral, structural, etc. To me, specific to JavaScript, there are two camps. One camp is specifically designed to deal with the evils and peculiarities of JavaScript, such as Singleton Pattern for global variables, Module Pattern for clear separation of private and public variables; The other more conforms to the general object-oriented thinking, such as Factory Pattern, Composite Pattern.

In the following, we will only take a look at the JavaScript specific patterns.

Singleton Pattern

You may have been using the Singleton pattern all the while. In its simplest form, a singleton looks like this:

var Person = {
name: "John Doe",
age: 30,

talk: function(){
},

wak: function(){
}
}


That is it. An object literal that groups the attributes and methods together into one logic unit. Or namespacing.

Singleton can be used as a page-specific wrapper.


Project.page1 = {
variable1: xxx ,
variable2: xxx,
init: function(){

}

};

document.ready{
project.page1.init();
}

Module Pattern

Module pattern is a more advanced singleton pattern, in that it separates private members from public ones. Module pattern has been cemented by the blog post A JavaScript Module Pattern.

A typical module pattern has the following elements:
a) A closure set up by anonymous functions;
b) private members, all declared as local variable with var ;
c) public members inside the return block, returned as an object literal ;

JavaScript uses anonymous functions a lot:


(function() {

// ...

}());

The above creates an anonymous function, it also attaches a pair of parenthesis so the function can be executed right away.

Inside the anonymous function, we set up closures to separate private and public members. In a singleton pattern, everything is equally accessible and readily to be modified. Closures however set up outer and inner scope in a function; The outer scope is created by the outer function that wraps around a set of (private) variables and functions marked by the keyword var, the inner scope/functions live within the larger function and have access to all the variables, only those functions and variables returned by the outer functions are public.


The following is a dummy module pattern:


Module_Person = (function () {
//private sections
var name = "John doe";
var age = 30;

var talk = function () {
};

var walk = function (x) {
}
// public sections
return {
statement: "I am a person created in the module pattern",
publicTalk: function () {
alert(this.statement);
}
}
} ());

Module_Person.publicTalk();

alert(Module_Person.statement + " statement");

Lazy initiation

Module pattern is great and it gets executed as soon as the script loads. However sometimes you may not want this to happen, especially if the module is resource heavy. In this case, you may want to modify the pattern further more so you have full control when it gets instantiated.

The way do it is to future package your pattern, put all of the module instantiation into a constructor function, and add a instance variable, then in the return statement check if the module has ever been instantiated, if yes, return the instance, if not create one and return.

With this in mind, the above module pattern can be modified into a lazy loading one.


LazyLoading_Module_Person = (function () {

var person=null;
//private sections
function module_person () {
var name = "John doe";
var age = 30;

var talk = function () {
};

var walk = function (x) {
}
// public sections
return {
statement: "I am a person created in the module pattern",
publicTalk: function () {
alert(this.statement);
}
}
};

return {

getPerson: function () {

if (person === null) {

person = new module_person();
}

return person;
}
}

} ());

LazyLoading_Module_Person.getPerson(); // get instantiated the first time

LazyLoading_Module_Person.getPerson(); // simply return the instance






Chaining

We have seen so often the weirdly appealing operation chain in JQuery, where the dollar sign ($) forks together a long sequence of operations on a set of elements. Chaining serves two purposes: less code and more efficiency, in that to do several things on the same object, the object needs to be fetched only once and operations can be piped onward in a streamlined fashion.

JQuery has made chaining a well-known JavaScript pattern. How does it work?

In JavaScript all objects are passed as references, and all objects inherit from their prototypes.

Thus you can create a operation chain by bassing the reference back by calling return this at the end of every method

As a practice, I created my dummy operation chain


//construtor
function Clean_Talk(text) {
this.talk = text;
}

// function prototypes
// return the reference to This back at end of each method
Clean_Talk.prototype = {

modify: function () {
this.talk = "Cleaned Talk: " + this.talk;

return this;

},

filter: function () {
this.talk = this.talk.replace(/badword|anotherbadword/gi, "****");
return this;
},

speakNow: function () {
alert(this.talk);
}

};

var clean_talk = new Clean_Talk("I said some badword. Can you filter it out?");
clean_talk.modify().filter().speakNow();


Outside of JQuery, we found other elegant use of chaining at http://ajaxian.com/archives/javascript-asynchronous-method-queue-chaining

Source:
Pro JavaScript Design Patterns
Question: Is the JavaScript languge functional or object oriented?
Answer: Both. And more.

Question: Should we use JavaScript primarily as a functional language or object orientated?
Answer: Depends (on your skill, taste, project needs).

Question: Are there examplary libraries that can be said as primarily functional or object orientated?
Answer: Well, most of the libraries are like JavaScript itself in that they support multiple programming paradigms. However, JQuery has a strong flavor of functional programming, while Ext.js is a completely object oriented javascript library.

Why? How?


First of All, object-oriented vs. functional

In OO programming, nearly everything is considered an object that has its set of state and behaviors. For example, a person have name and gender, a person talks and thinks. Classes are used to define the objects, states and behaviors are translated in members and methods. OO is considered as using classses and objects to mirror the real world of inter-connected hierachical entities, and break down complex system into smaller more manageable elements.


In functional programming, instead of objects, functions are the beginning and the end and everything in between. Functions are the building blocks of the programming. Individual functions are defined to perform individual tasks, such as compute, sort, translate; functions can be passed as arguments and results; functions can call themselves (recursion).

Objected oriented programming is the fashion of the current day programming, many languages are object-oriented languages,such as C#, Java; however, computer programs started out in functional programming, and lately functional programming languages are also staging a comeback, i.e., F#.

Objected-oriented and functional do not necessarily exclude each other.The Language Integrated Query (LINQ) feature, with its many incarnations, is powerful use of functional programming in .NET.; Java is sometimes said "impure" in Objected-oriented styles; While F# can use .NET types and objects and object-oriented style of programming.


JavaScript, functional?

Well, you may have recognize the characteritics of object-orientation and functional programming in such typical descriptions of JavaScript:

In JavaScript functions are first-class objects;

"JavaScript is fundamentally about objects. Arrays are objects. Functions are objects. Objects are objects. So what are objects? Objects are collections of name-value pairs. The names are strings, and the values are strings, numbers, booleans, and objects (including arrays and functions). Objects are usually implemented as hashtables so values can be retrieved quickly."

Private Members in JavaScript


Functions as first class objects


A lot about JavaScript functions fits in the bill of functional programming, the most obvious of which is anonymous functions that are widely used in event handlers and ajax calls.


$('#target').click(function() {
alert('Handler for .click() called.');
});


The flavor of functional programming in JQuery

The scent of functional programming in JQuery is particularly strong. There are three things make it so:
1) the JQuery variable, the magical dollar sign ($); 2) css selectors; 3) functional chain.

In JQuery, code like this is everywhere:

$("div.test").add("p.quote").html("a little test").fadeOut();


Dive into it, we can make three notes:

1) $, the biggest and all-encompassing jQuery object, started the chain. $ essentially is the wrapper of DOM object.
2)$ fetched the set of elements that are selected by the css selector using the expressing "div.test", meaning all divs with the class name test.
3) Chain operations a) add a little paragraph with class name quote; b) add a little html text c) have the div fade out.


The above three things typical of JQuery makes JQuery a perfect candidate in the family of functional programming; more precisely or nerdily, a monad.

The following is a definition of monad struction in Wiki:

"A monad is a programming structure that represents computations. Monads are a kind of abstract data type constructor that encapsulate program logic instead of data in the domain model."

/Monad_(functional_programming)


JavaScript, object oriented?

On the other hand, JavaScript is also perfectly object oriented. Almost everything in JavaScript is an object. And objects in JavaScript are extremely dynamic and meallable.

In JavaScript you can create an object in a few ways, the easiest is simply using call:


var x = new object();
x.name ="x";
x.tellName = function (){
alert(this.name)
};

Or you can use literal notation:


var x = {
name : "x",
tellName : function(){
alert("my name is " + this.name)
}
};


You can also accomplish inheritance in JavaScript in a few differnt fashions. For example, prototypal inheritance


function Person(name){
this.name=name;
}

Person.prototype.sayName=function(){
alert ( this.name);
}


Girl.prototype = new Person; // Here's where the inheritance occurs

function Girl(name){
// Let the Person function initialize the name by calling parent class' constructor
Person.call(this, name);
}

Girl.prototype.sayName=function(){
Person.prototype.sayName.call(this);
alert( "hi, I am a girl. my name is " +this.name );
}


var peter = new Person('peter');
peter.sayName();
var mary = new Girl('mary');
mary.sayName();


So in the above, we created a base class called Person, immediately we create a child class
called Girl. The inheritance takes place by set the prototype of Girl as new Person. We also
have the Girl inherit the Person's contructor by using

Person.prototype.sayName.call(this);


Lastly we overwrite the base class' sayName method by define its own.
function Girl(name){ 
// Let the Person function initialize the name by calling parent class' constructor
Person.call(this, name);
}




Ext.JS as an object-oriented JavaScript library

The Ext framework is completely fashioned around the object-oriented programming model. At the top of Ext library is the Ext namespace that encapsulates all classes, signletons and utiliy methods.

In new ext.js 4.0 library, the class system is as the following:




Take a look at Ext.Panel, which has the following hierarchy:


Let's look at some code of inheritance in Ext.js.

Ext.ns('MyApp');
/**
* @filename sillyPanel.js
* @class MyApp.sillyPanel
* @extends Ext.Panel
*/
MyApp.sillyPanel = Ext.extend(Ext.Panel, {

initComponent: function () {
var config = {
title: 'A silly Panel',
width: 120,
items: [{ html: "Nothing serious. A silly thing"}]
};

//Reusable config options here
Ext.apply(this, config);

// And Call the superclass to preserve baseclass functionality
MyApp.sillyPanel.superclass.initComponent.apply(this, arguments);
},
addSomethingExtra: function () {
}

});

A few observations from the above code sample of Ext inheritance

1) Namespace declaration. Ext.ns('MyApp'); Ext.ns is a shorthand for Ext.namespace. With a call of Ext.ns, it will create an object with the name supplied, if it does not already exist.

2) Ext extend is the utility function that implements class inheritance in the Ext framework.


3) Inside the extend, you provide the base class from which you are inheriting, and the extension details as the second argument. For more details on create Ext.js extensions, please view the Ext.js api.

To display the above coded silly panel on a page, you simply create a new silly panel on the Ext.onReady event.








My app tset page













Well, this concludes my rambling on the functional and object-oriented side of JavaScript,and my dabbling in features of JQuery and Ext.JS. In short, JavaScript is really a hodge podge of things, it really is flexible and mess. It supports a varity of programming styles, a lot of times you can get along not worrying about which camp you are in, but eventually as projects grows and your knowledge grows, you may need to think deeper and get to the root of why and how everything
happens in the way it does.

Source:
Functional vs. Object-Oriented JavaScript Development
JQuery: the very very basics

1 comments:

This keyword in JavaScript

11:28 AM Xun 1 Comments

"This" is a very important word, even my son knows. My son is nearly 2 years old, he uses the this keyword all the time. This, this! I want this! He says, he cries. Sometimes he points, so we'd have no problem figuring out what this is; Other times, he does not, which we'd soon be out of our wits guessing, and we get frustrated quickly.

Turned out in JavaScript, this is as important and frustrating as it is widely almost overly used. Understanding this is a key in correctly using JavaScript.


The Window Object
this without a context, or this in a normally functional call, refers to the window object, the container / owner of all. Try the following code:


function WhatIsThis() {
alert("This is " + this);
}





The DOM Element

This is often attached to an DOM element for event handling, click, key up, key down, etc. Do anyone still use those inline event handlers as the following ?

click me



In the above, the owner of this is the link being clicked.

Inline event handler has become pretty much a thing of the past. In JQuery, we often handle event as such:

$("p").click(function () {
$(this).slideUp();
});
$("p").hover(function () {
$(this).addClass("hilite");
}, function () {
$(this).removeClass("hilite");
});

And this is tied directly with the dom element that triggered the event.


Functions

Many, many times, What this means completely depends on how a function is used. And functions can be used in many, many ways.

Functions inside of an object as a member methods


Object in JavaScript is as versatile and overreaching as a function. When you define a function inside an object, it becomes a member method for the object. And if you say this inside the method, this refers to the object, who "owns" the method.


var Person = {
message: this.message + " This is me",
displayMessage: function () {
alert(this.message);
}
};

Person.displayMessage();






Function as constructors


Functions can be used as constructors. For example, the above can be rewritten in the following fashion:


function Person(message) {
this.msg = message;

this.displayMessage=function () {
alert(this.msg);
};
}

var p1 = new Person("hi, how are you");

p1.displayMessage();





.apply() and .call()


So what this refers is really up to the context. What if we really want to get this right done to the object in a global context? ...?? Sorry, not being clear, so illustrated in code:

var p1 = { message: "hi here is P1 talking" };

function displyaMessage(message) {
alert(message + this.message);
}

displyaMessage(p1, "Who is talking?");

What would you get for this in the above function? Undefined!!!

Wouldn't be nice if you can make sure this actually refers the object itself (p1) instead of the window object? JavaScript
.call() or .apply() can do just that.

Now try the following:


var p1 = { message: "hi here is P1 talking" };

function displyaMessage(message) {
alert(message + this.message);
}


displyaMessage.call(p1, " Who is talking?");

displyaMessage.apply(p1, [" Who is talking"])





viola!

.apply() and .call() do the magic. With them, the this keyword is grounded to the object that is supplied to the function call as the first argument.

.apply() and .call() work similarly, the only difference is that .apply take array in the second argument, works nicely when you have to supply multiple parameters to the constructors.

So much about this!

Source:
Scope in JavaScript

1 comments:

JavaScript: the good part, the bad part

12:39 PM Xun 2 Comments

Recently (belatedly) I stumbled upon the excellent speech JavaScript: The Good Part" by Doug Crockford. There, like a mouse chasing cheese, I followed the trail
of "JavaScript: The Good Part", I devoured the book, I checked out the blog, I went through the slideshow. All of them by Doug Crockford.

By the way, if you do not know who this Doug Crockford is (after all, in our tech world, we are often more obsessed with products with funny names, twitter, lulu, hulu ...,
than the people who are behind the products), he is the one who "discovered" JSON. Actually, he was put off by the eccentricities of JavaScript first, then in working with
JavaScript further, he reliased the effectiveness and expressiveness (the good part) of JavaScript, thus the book. In a moment of "Aha", he also realised the
power of JavaScript literal notation, thus he set up json.org to publish and promote JSON.

Now back to JavaScript.

The Bad Part

Global Variables


The greatest evil of JavaScript are global variables. Global variables are convenient in a small program, however can be too quickly, easily, accidentally or intentionally
turned into a nightmare. First, global variables are slow; second, they can be easily overwritten and manipulated (an invitation for crosssite javascript attack);
third, variables are by default global, which makes them so evil.

Global Variables can created in the following three ways:

a) Proterties added to the global object (the window object)

window.x = 0;

b) Variables created outside a function


var x =0 ;



c) Variables created accidentally, i.e., variables being used without being declared,


x= 0;


or

var x = y = 0; // in this case, y becomes the accidental global variable because it is not declared first



adds and substracts and concatenates

JavaScript has very few primitive data types (number, string, boolean, object). Pretty much everything falls into the category of JavaScript; JavaScript also
does not require/need you to specify the data type of the variable; JavaScript also has a high tolerence for operating (adding, concatnating) on variables of different types. All of
which contributes to the sometimes strange behavior of adding and concatenating.

What will you get if you this?

0 + "1" // return "01";
"3" + 1 // return "31"


What happened? Because there is a string in the adds, JavaScript interprets as you want to concatenate two strings.

"3" -"2" // return 1

What happened? JavaScript assumes no substraction should occur between two strings, thus convert them to numbers for you!

JavaScript simply tries too hard.

Semicolon insertion

Another manifestation of JavaScript's evil is in Semicolon insertion. This again results from that JavaScript does scream or yell when you write
bad code (eg., forget your semicolon), however from behind the scene, it tries to remedy this by inserting the semicolor for you.

So what will you get for the following:

function add(a,b)
{
return
a+b
}



Oh-oh, you get nothing. Because JavaScript tries too hard by adding semicolons everywhere there is line break:

function add(a,b);
{
return;
a+b;
}


So please write your code correctly. Good style matters.

function add(a,b){
return a+b;
}



typeof

JavaScript let you check the type of your object by using typeof. Somehow, the typeof does not always act rationally either.

Try the following test:

typeof null === "object"; // returns true. But should it not be null type?
typeof [] === "object"; // returns true. But should it not be array type?

with and eval

with is bad. eval is evil. People all say so.

with is slow and confusing.

eval is slow too. It also can become an easy target of crosssite javascript attack.

phony arrays

JavaScript arrays are really hashtables that is accessed by the keys. This made it a bit slower.

== and !=

Because JavaScript's habit of type coersion, it is not easy to determine two things are indeed equal or otherwise with == and !=. The recommendation is using === and !== instead.

Consider the following, what will you get?

"1" == 1 //returns true  
1 == "1" //returns true
"" == "0" //returns false
NaN == NaN //returns false
NaN !== NaN //returns true



false, null, undefined, NaN, ""

Another bad part of JavaScript is that it has too many indistinguishable fals-y values: false, null, undefined, NaN, "", they all mean one way or another, false (as opposed to true),
no value /empty object (null), do not know what you mean (undefined), not a number (NaN), empty string (""). But, gosh, aren't they confusing?

The worst of them all is NaN, it is not a number, at the same time, it is a number. It is just, ah, not a number that is valid.


You may want to continue with your list about the bad that is JavaScript ...

Now, the Good Part.


That JavaScript is thriving today and becomes the most important language as it is the langugages of browsers testifies the goodness of JavaScript,
that it transform itself in the multiple excellent libaries such as JQuery and Ext.js and YUI while Java Applet failed without a trace says the effectiveness
and efficiency of JavaScript.

Its virtue must be numerous.

Functions

The best part of JavaScript is its extreme flexibilities of functions.

Functions are first class citizens (VIPS) in JavaScript. It can be used as you normal procedural functions;
a member method in an object; constructors. It can be anonymous, then the trendy name of lamda functions; it can be self-evoking; Functions has varying
depth of scope. You can create closures with functions ...

Procedural function

function add(a, b){
returns a+b;
}


Function as a member method:

  var addThem = 
{

add : function(){
return 1 + 2;
}
}

alert(addThem.add());


Functions as constructors:

 var Add = function (a, b) {
this.add = function () { return a + b };
}

var addMe = new Add(1, 2);
alert(addMe.add());

Anonymous Functions:

We often see them in event handlers and ajax calls:
 $('#target').click(function() {
alert('Handler for .click() called.');
});


 $.ajax({
url: "test.html",
context: document.body,
success: function(){
$(this).addClass("done");
}
});



Closures

Closures has been a mysteriously widely used word. What does it mean? In my understanding, it means an outer function create a closed
context where there are a set of variables that can only be accessed by its inner functions. This is the base for creating private members in
JavaScript. For example:

 function Add(a) {
var b = 2;

var add = function () { return a + b; }
return add;
}

var addNow = new Add(2);

alert(addNow());


Loose Typing:

In most languages, strong typing is strongly encouraged, because it gives you a sense of security that all of your variables are correctly typed, therefore type-related errors
can be easily found out and avoided. However, Mr. Doug Crockford said no. Strong-typing does not save you from good-old testing, besides any type
related errors can be easily found out. With the loose typing of JavaScript, you loose the rigidity and headache and overwork because you have to always
make sure you are on the correct side of types, it is libarating.

Agreed.

JSON

Last but not the least. JavaScript gives us JSON. The lightweight transimission of data. The now universal standard.

2 comments: