What has happened so far, in JavaScript, In 2011?

8:22 PM Xun 2 Comments

In the mere sense of numbers, 12/31/2011 is probably not that different from 1/1/2012. But we are humans. And we humans like to ascribe meaning to everything, especially at the beginning and the end of everything. At the end and the beginning of every year, we like to create reviews and make resolutions, reflect on the past and gaze into the future.

So in this reflective mood, I look back to see what has happened and has been happening with JavaScript, in the year of 2011.

Html5 and CSS3



Image from http://feedgrids.com/originals/post/building-a-better-website-with-html5-css3/

Ah, Html5 and CSS3 are still raging fire. Html5 is nothing new, nor is CSS3. Nor are they becoming official or the standard of the day. Both had been in the working for years and as of now are still under development. Neither are radical departure from their predecessors. Rather, HTML5 builds upon the previous versions of HTML, 4, 3, 2 and 1. It aims to provide web with easier and standardized delivery of multimedia, make our web a natural canvas for everything graphical and animated; CSS3 also aims to enhance the web as the most impressive presentation form, allow things more visually pleasant and effective and yet less burden on developers and designers, thus round corners, box shadows, pretty borders and damn good-looking menus with nothing more than some CSS3.

Yet without JavaScript, Html5 and Css3 are pretty much just some more tags and decorations, they can hardly, if ever, render awe and wonder and the sensation of a live web. For example, check out the follow app that uses graphics libraries like WebGL that in its core are a JavaScript library that made 3D graphics alive in a browser without any plug-ins.

Brain Surface and Tractography Viewer



ECMAScript

While JavaScript and all of its siblings such as JScript, ActionScript are really ECMA script in implementation, ECMA script has always sounded wierd, like ""ECMAScript was always an unwanted trade name that sounds like a skin disease (aka ECZEMA)." (Wiki ECMAScript.)

As JavaScript is as thriving as the web, ECMAScript is also working hard on its new project code-named "Harmony", on the helm of publishing its fifth edition in June 2011. The goal for Harmony is to make JavaScript a better language ((yeah, how many people still say with reason that JavaScript sucks) for writing complex applications and libraries, more testable and more modular, more inter-operable, adopting de facto standards where possible, that is, do not throw your granddaddy under the bus even though sometimes he behaves like an old fool.

Source:Harmony

Dart

Like the ECMAScript folks and the rest of JavaScript community, Google too has a lot of strong opinions about the state and future of JavaScript. In October 2011, Google unveiled a new web programming language named "Dart" while vented their frustration with JavaScript through a leaked and now widely read memo at Github. The memo reads:

Javascript has fundamental flaws that cannot be fixed merely by evolving the language. We'll adopt a two-pronged strategy for the future of Javascript. That is: a) keeping harmony with ECMAScript Harmony; b) develop Dart and push Dart to eventually become an open standard and be adopted by web developers and all modern browsers.

So far, all modern browsers (excluding Chrome, of course): IE, Firefox and Safari have declined to adopt Dart. However, whether Dart would win the battle is anybody's guess.


Node.Js

In 2011, everyone has said one thing or two about Node.js, quite a number of projects, applications and companies have adopted Node.js. What is Node.js? What is it for or not for?


Image from http://habrahabr.ru/blogs/webdev/108241/

"Node.js is a platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices."

Source:node.js

node.js is not really a JavaScript, but it has the look and feel of JavaScript. In fact, node.js deliberately adopted JavaScript's syntax to ease the pain of learning yet another framework/language/whatever and to make the server and client side script work with less friction.

It also uses the same catchphrases that we use to describe how great JavaScript is: event-driven, asynchronous. Yet, node.js is true, or more true, to these claims. On the web, JavaScript does not drive, what drives are web servers, IIS, Apache. Web servers serves an ever-increasing and crushing amount of traffic and requests by threading, thread this to fetch data, thread that to get a file. Yet there is a limit as to how many threads that a server can generate, and threaded IO is not non-blocking (how long you have to wait behind 6 people for your doctor?). So node.js aims to solve the problem. Why wait? Let's serve you as soon as you come. Let's just create as many connections (web servers) simultaneously, sending and taking care of many mini-requests as soon as possible. node.js accomplishes this by dealing directly with web sockets and using closures for non-blocking.

node.js has made a splash. node.js needs bigger players (as big as twitter, as fast and furious as twitter) to flex its muscles. For linus and mac users, you are ready to play with node.js to check out its potential. For windows, hold on a minute or a year.

JavaScript Frameworks for Mobile
If you noticed how hot All Is (IPhone, IPad, etc.) is, or how busy all Androids are (Google just offer free android development classes), you surely know all the sweet spots for development for mobile. JavaScript has geared for and gravitated towards mobile. There are oh so many JavaScript frameworks now for mobile that can deftly provide responsible and touchable and mobile solutions. JQuery mobile is by far the most popular, the other ones are MooTools mobile, Jo.



Source:JavaScript Frameworks for Mobile

2 comments:

XSS: Cross Site Scripting attack

9:30 AM Xun 1 Comments

XSS (Cross Site Scripting), now and then

In Nov., users of Facebook were "offered an opportunity for something (a shocking must-see video? a free iphone?)" if they could copy and paste a line into their address bar. A number of them did, they were then bombarded with explicit and violent content. For 24 hours, the content spread throughout the site and forced Facebook shut down malicious pages, and roll back any infected user accounts.

Facebook is a fertile ground for XSS infestation. It is only a surprise how blatant and "old timer" the manner of the attack (Yes, free iPhone!). Only in May, Facebook rolled out a "Self-XSS protection" security feature to protect users from such spam and scam, on the wake of three consecutive XSS attacks.

The first was passed as stories posted on users' wall, with a bit of iframe code embeded.



The second one affected a Facebook "channel" page used for session management, also a bit of JavaScript is injected into the url.


The third one involves a video posted through a Facebook app. To unsuspecting eyes, the video is nothing unusual. However, launch of the video also quietly unleashed the coded attack behind. Code screenshot shown below:



Source: Recent Facebook XSS Attacks Show Increasing Sophistication

As a matter of fact, Facebook is faced with clickjacking and scam campaign on a daily basis.

More and more, with ever faster pace, we are willingly / unwillingly make ourselves part of corporate data, for better or for worse. Every tidbit information about ourselves, significant or trivial, name, addresses, phone number, social security numbers, credit card, our friends' names, are fed, mined, aggregated into advertisers' database. Anything we do not directly type into some websites are inferred, stored and updated in the corporate databases too. The explosion of online activities and information means many things. It makes Facebook the crown jewel of social networks, it also subjects Facebook to intense scrutiny and daily attack. It crowns JavaScript the language of the web, it also turns JavaScript into the most widespead tool of malicious scripting.

In 2005, MySpace was about as popular as Facebook is today, and XSS attacks were as little known as it is widespread today. Then in Dec 2005, the security world is awoken to worm named "Samy". The samy worm was designed to spread from one user profile to another, and it infected more than a million users in 24 hours. As potent as it was, the Samy worm was set out to make a name. So it did. It made a lasting impact, the reasearch into xss attacks exploded, unfortunately so did the effort in exploit web vulnerability in the form of XSS attacks.

In 2006, XSS attacks got inventive. Intranat hacks, keystroke tracks, JavaScript port scanners, traojan horses, etc. were disguised in every form that contains some html / javascript code, emails, websites, chat rooms, message board. Security holes were discovered in more than 70% of web sites.

Fast forward to today. In early 2011, IMB published a white paper reporting on their research of XSS attacks. The research used a sample group of about 675 websites, most of them Fortune 500 companies. The method used is a non-intrusive, shallow crawling of the sites involved. Therefore no logins, no deep digging into sites.

The result is disturbing: 14 percent of the sites, through their own or third part JavaScript vulnerabilities, could Infect with Malware and viruses, Perform Phishing attacks on users of these sites, spoof web contents, hijack users' web sessions and perform action on their behalf. The likelihood that a random page on the internet contains a client-side JavaScript vulnerability is approximately one in 55.



(Source: Close encounters of the third kind).


The route of XSS attack

Attacks may come blantantly or stealthily. If your browser is popping up blinking ads saying you are a jackpot winner;if you were unexpectedly led to violent, sextual content while browsing news, you can correctly assume that you are XSS'd; Or you could be completely blindsided until one day your bank told me that your information may have been stolen (this has happened to me).

How did these attacks happen? You may come up with a list of maybe answers. Maybe one day you opened up an email, which led to a suspicious website; or maybe you opened an attachment you thought it was sent from your friend; or maybe you followed the link in the posts on your friend's wall, through your smart phone, your mobile tablet ... One way or another, it is either that: a) you were led to visit a malicious website; or b) you visited a trusted site yet the site was hijacked and was planted a seed of malicious attack; or c) you clicked a link that is crafted with malicious script; d) a security hole of your browser was exploited and javascript was injected.

Elementary XSS details

The chase never ends. You plug one hole, more comes up. XSS is filled with new ways of vulnerability exploitation and code injection. However, something fundamental remains.

There are two major flavors of XSS: non-persistent and persistent. Non-persistent attack happens when a url or form is injected with malicious code, however it is not persistent, it is click-based/event based; Persistent attacks are conceivebally more dangerous, they can cause lasting damage because the code is stored as a cookie or in database by the website, and affect all users who visit the site. In this case, users are defenseless. Outside of the persistent/non persistent categorization, domain-based attacks, which can be both persistent and nonpersistent, are also prevalent. Domain-based attacks are exclusively on the client side and are engineered to exploit vulnerabilities in the html document (script, DOM handling). The vulnerability could be both from the javascript implementation or browser interpretation.

XSS through urls

Script injection frequently happens on the url level. It is first made well known by the security expert Amit Kleint in DOM Based Cross Site Scripting or XSS of the Third Kind


It is a common pratice that we embed bits and pieces of information in the querystirng of an url then parse it in the JavaScript and do something accordingly. As in the example listed by Amit Kleint.




However this serves an opening for code injection for hackers. They can simply call a url as such:



As now most developers are aware of danger of this, hackers are also more skillful disguising their intent. So the above url will be more likely look like below:





(Notes: To my great surprise and annoyance, both of the above url calls execute immediately in blogger. I had to take screenshot of the code. Below is the screenshot of the script gets executed in blogger:)



XSS through input forms

Data can be passed through urls. It also frequently passed through input forms, through input textboxes, textareas. Search boxes were and still are hackers' first bait. They often execute scripts that automatically submit a form and test for opportunities. If a search for "blah" returns a page that says "Sorry, a search for blah is not found", they could then subsitute the "blah" with a test script:
<script>alert('XSS')</script>
; if the page excuted with a alert box, bingo, they can plan their atrack right now; if no, they can inspect the JavaScript cleansing machanism, then circumvent it.

As a matter of fact, because of the danger of inputting malicious code, many websites use stricter user input validation and output sanitation, encoding and escaping special characters. As a result, hackers also have camouflaged their scripts by playing with quotes, different encoding method.

The Web Application Hacker's Handbook: Finding and Exploiting Security Flaws


XSS through images, flash, pdf, videos. You name it.

On the internet, every object can become a source of script embedding, images, flash objects, pdfs, videos, you name it! And unless you disable JavaScript, script can be excuted upon the event of loading, unloading, or when you thought you were merely watching an harmless video, as in the case of Facebook users in April.

Modern email programs, such as GMail, outlook, normally do not block images from displaying unless your explicitly set permission. Why? Because, the src property of images can either be direct injected with script, or indirectly linked to a malicious site.

Flash object too. Adobe just released a Flash Player update in response to reports that a cross-site scripting vulnerability is being exploited in the wild in active targeted attacks. (Source: Hackers exploiting Flash Player XSS vulnerability


Parting words

There is more, so much more, to talk about XSS, even just to scratch the surface. Blunt forced XSS, XSS filter and evasion, XSS detection and prevention, etc. And it is constantly evolving, the attacking and defending side of XSS. We can say nothing for sure, other than that, XSS is a clear and present and ever-escalating danger, just look at Facebook today.


Source:
XSS Attacks: Cross Site Scripting Exploits and Defense

1 comments:

JavaScript prototype

1:21 PM Xun 1 Comments

I must confess: for the longest time, I did not know anything about JavaScript prototype, nor did I care. I was just programming my way in blissful ignorance, however the frequent talk of and reference to JavaScript prototype finally got me.

Turned out prototype is so fundamental to JavaScript that not knowing about it makes you de-facto handicapped, at least when you go deeper and deeper in the rabbit hole that is JavaScript.

What is prototype? As the term implies, it is a model or process to be replicated or learn from.
From (Wiki: Prototype)

Everything, every product has a prototype. Every car has a prototype, every car built from the prototype automatically inherits the functions from the prototype; Every JavaScript object has a set of prototypal properties and methods, every instance of the object carries on the prototypal properties and methods by default. An array has prototypal methods such as
concat
,
constructor
,
every
,
filter
,
forEach
; A string has a different set of methods for string manipulation such as
charAt
,
big
,
blink
,
bold
.



How do you inspect the prototype of an object?

For objects, you can use
Object.getPrototypeOf
in most modern browsers (IE 9 and above, Chrome, FF); Or simply
__proto__
in non-IE browsers for both objects and other JavaScript primitive data types.


var a = {};
var pa = Object.getPrototypeOf(a);
console.log(pa); // Object

var b = [];
var pb = Object.getPrototypeOf(b);
console.log(pb); //Array

var c = "I am a string.";
var pc = c.__proto__;
console.log(pc); // String

//custom object
var Person = function (name) {
this.name = name;
this.sayName = function () {
console.log (this.name);
}
}

var peter = new Person("peter");
var pp = Object.getPrototypeOf(peter);
console.log(pp); // Object


Alter the prototypal landscape

JavaScript prototype is a powerful thing because it dedicates the genetic make-up of all of its instances and decendants; it is also amazingly meallable, open to alteration and manipulation.

Take the above
Person
constructor for example. The
Person
's prototype is an Object, therefore any
Person
, in our dummy case
Peter
, is pre-loaded with all the methods defined in an object prototype, including
toString
,
toLocaleString
. Therefore peter not only can call its local method sayName, it can also check out the methods in its prototype chain
toString
,
toLocalString
.


peter.sayName(); // peter
peter.toString(); // Object
peter.toLocalString(); // Object


How does peter knows there is a
toString()
method without defining it? Here comes in the concept: prototype chain. What does that mean? It refers the chain of look-ups, the route of upward searching in JavaScript. When a method or a property is called, JavaScript starts searching locally, if find it, great! Execute and return!; if no, one step further, it goes to the prototype of the current object; if still no? It reaches further. So it goes, until it reaches the root of the chain.

A prototype chain is illustrated from the image.




Briefly,

1. JavaScript starts the search with object "a".

2. If no, JavaScript then visits "A.prototype" (the prototype of object "a") and looks for the property.

3. If still no, JavaScript then check "B.prototype" (the prototype of "A") and finds the property. This process of visiting each object's prototype continues until JavaScript reaches the root prototype. This series of links by prototype is called the "prototype chain".

Image and description from Document Object Model Prototypes, Part 1: Introduction

As for the
toString()
method for
peter
, you can see the path of search here:



(Prototype chain is the base of JavaScript chaining, exemplified by jQuery; Prototypal chain has some performance implications. The deeper the root is, the deeper the search goes, the heavier performance penalty is, but that is a topic merits an article of its own.)

Back to the
Person
constructor, it defines a method
sayName
. And now every instance of Person has its copy of
sayName
method. This in itself is a bit of expensive, especially if you have a very complicated
sayName
method; in contrast, make it part of the prototypes makes it more memory efficient. To do so, we get rid of the
sayName
method in the constructor, and add it to the prototypal arsensal:


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

Person.prototype.sayName = function(){
console.log(this.Name);
};

var mary = new Person("mary");
mary.sayName(); // mary

This is prototypal inheritance in its simpliest form. And we just successfully changed the prototype of the object
Person
.

If we can make methods part of the prototype, so we can make properties. This can be quite useful if you want to set up some default properties for the object.


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

Person.prototype.sayName = function(){
console.log(this.Name);
};

Person.prototype.canTalk = true;

var mary = new PersonP("mary");
mary.sayName(); // mary
console.log(mary.canTalk); // true


JavaScript built-in objects

All the above deals with a dummy customized object. However, it does not mean you cannot add prototypal methods with JavaScript built-in objects, such as
Date
, such as
String
.
Date
is a usual suspect, because people like to manipulate Dates.

For example,


Date.prototype.isAprilFool = function(){
return (this.getMonth() == 3 && this.getDate() == 1)
}


From Date prototype is april fool

Now you have the IsAprilFool judgement call.


var today = new Date();
today.isAprilFool(); // false


Easy!

JavaScript inheritance

Javascript inheritance has many forms in subtle or unsubtle variations. It is the topic of constant and ongoing debates. Nearly all forms of JavaScript inheritance are careful studies of JavaScript prototypes, be it classical or peudo-classical or prototypal inheritance.

Mr. Crockford started with classical, and had written about it in Classical Inheritance in JavaScript, then he is convinced with the superiority of prototypal inheritance, and wrote it at here:Prototypal Inheritance in JavaScript. A lot of other people also have produced beautiful articles even libraries with their own version of extend or inherit, for example, John Resig's Simple JavaScript Inheritance and Defining classes and inheritance from the Prototype JavaScript framework.

But it is late now, I already used up my lunch time plus some other time that is slotted for my work. So, so long.

Source:

The prototype object of JavaScript
http://msdn.microsoft.com/en-us/scriptjunkie/ff852808
Understanding JavaScript Prototypes.

1 comments:

JavaScript: some good books

11:20 AM Xun 1 Comments

Even within the highly concentrated little world of JavaScript, the amount of information and knowledge can be overwhelming. And they rush to you in every kind of media: books, blogs, online articles, video presentations, websites that dedicated to collect more source code than you can ever possibly read or even browse through. If you were like me, you probably would just jump from page to page, led by the guiding hand of google, then get lost from traveling along the circulous, endless-branching, criss-crossing paths.

At times like this, books may offer you an anchor. If you are patient enough, good books may even offer you great many ah-ha moments, cystal clear insights into concepts that were murky and clouded by competing, half-baked opinions on the web.


With regards to JavaScript, the following books are on my list of good books:


JavaScript: The Good Parts
by Doug Crockford


Available on amazon. However you can also read free here.

Crockford is an eloquant speaker and writer. His insight and keen observation made it possible for him to "discover" the gold of object literal notation (JSON) in its flexibility of representing any structure in simple, succinct and accessible manner.

In JavaScript: The Good Parts, Crockford presents JavaScript's blunders or things that meant for good, however went bad through entrenched bad practices; yet through evil and less ideal, he illustrates how effective, dynamic and liberating and expressive JavaScript can be. Where Java Applet fails, JavaScript shines and wins as the language of the web. Crockford also gave a series of talks surrounding the goodness and badness of JavaScript. All of the videos can be found, you know, at YouTube.


Pro JavaScript Techniques
by John Resig


John Resig is the number one celebrity of the community. Young, penetratingly smart, he created jQuery. He aslo rolled out a bunch of books mostly about JQuery. This Pro JavaScript Techniques however is not JQuery specific, it addresses a wide range of best practices and advanced techniques, such as object-oriented JavaScript, testing and debugging, unobustrusive JavaScript, etc., then he illustrates his techniques with sophisticated real life examples, auto-complete search, image gallaries, an ajax wiki. I am sure the moment you put down the book, you will be able to put together a dazzling web site.


High Performance JavaScript
by Nicholas C. Zakas


Nicholas C. Zakas is also a highly recongnizable name. He is the principal front end engineer for Yahoo! He has authored accaimled JavaScript book Professional JavaScript for web developers and co-authored Professional Ajax. Nicholas also frequently speaks in various venus.

About the book. Fast, better, responsive web is forever the goal for any websites. With JavaScript growing in complexity and size, optimization through better coding, better DOM handling, code minimalization are more important than ever. So in the book: High Performance JavaScript, Nicolas illustrates various techniques, do-s and dont-s, to speed up page loading and eliminate performance bottlenecks. Rather than just saying you need to do this and that, he also back up his case by showing various performance metrics among different browsers.


Professional JavaScript for web developers
by Nicholas C. Zakas


The book features a very handsome Nicholas C. Zakas on the cover, which, in short order, is followed by a forward that succinctly yet beatifully captures the trajectory of JavaScript, and continues on to offer a glowing Why Nicholas' book is such a great book. Quotes blow:

"What Zakas accomplished with Professional JavaScript for Web Developers is singular: he treated JavaScript as a subject that is both serious and accessible. If you are a programmer, you will learn where JavaScript fits into the broader spectrum of languages and paradigms with which you're farmiliar. You'll learn how its sytem of inheritance and its intrinsic dynamism are, yes, unconventional but also liberating and powerful."


Pro JavaScript Design Patterns
by Ross Harmes, Dustin Diaz


Published in 2008, this book could be a little out dated to your taste. However, you can read to your heart's content to soak in all of the object-oriented patterns, and how can you apply those in JavaScript in real life examples. And if you are to design a complex JavaScript application, it is probably a good idea to think through your structure through the lens of those object-oriented design patterns.



JavaScript: The Definitive Guide
by David Flanagan

From the first edition in 1996, to the six edition in 2011, JavaScript: The Definitive Guide certainly passed the test of longetivity. It also says its enduring appeal to programmers, either novices or professionals. With each edition, the book shed some out-dated concepts and incorporates some new standards and pratices, which is great. I am sure The Definitive Guide is going to live for as long as JavaScript lives.

Oh, boy, the definitive guide is bulky, however it has very straight-forward structure: Core JavaScript, meant to be a JavaScript language reference, to me it can be a quick cheat sheet; Client Side javascript, gets into the implemenation business, JavaScript in action. To me, the first part is more valuable. The second part comes across as a little too simplistic or inadequate.

1 comments:

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: