Friday, December 31, 2010

Private Properties and Methods:

Javascript has no special syntax to denote private properties or methods. But the same effect can be achieved declaring variables or methods with keyword "var" in function or object scope. Below is an example concentrate on this concept:


// In MyObject all properties and methods are public, as there is no use of "var" inside object
function MyObject() {
   this.name = "Ravi Kumar";
   this.getName = function() {
      console.log(this.name) }
   }
var myObj = new MyObject()
myObj.getName() // Ravi Kumar
console.log(myObj.name) // Ravi Kumar


//Adding var will make name public
function MyObject() {
   var name = "Ravi Kumar";
   this.getName = function() {
      console.log(name) }
   }
var myObj = new MyObject()
myObj.getName() // Ravi Kumar
console.log(myObj.name) // undefined

Where as while returning private members of type Object or Array, you should note that, when we pass Objects or Array we pass it by reference. Hence while returning private Objects and Arrays we would be exposing them to further altercations. So for being on the safer side, while returning general utility for clone/copy should be used, with that whatever we return will not have any relation with the Private member.

Privileged Methods: Privileged Methods is nothing but method created in local scope of variables which has access to those variables. In above example getName is a privileged method. 

If you want to declare private members using object literal you should wrap it with immediate function as follows.


var myObj=(function(){
    var name="Ravi Kumar";
    return {
        getName:function(){
            return name;
        }
    }
}())

myObj.getName() // Ravi Kumar

Wednesday, December 29, 2010

Some More Patterns

Init-Time Branching: Minimizing computing as far as possible. For example browser features doesn't change over a session. Instead of checking browser features every time it's better to compute them once and according to that, update other utility function


Memoization: If return value of a function never change for given inputs, it's better to cache them in function as hashtable of serialized input params and outputs. Since functions are objects they can have there own properties and methods.


Configuration Object: It's better to use single object parameter against, multiple input parameters. As project grows, the requirement grows and number of input parameters grows. It's not a good idea to send too many parameters to a function, it's hard to maintain as well. Hence we can send an object which has key value pairs of input names and parameters, so that it's easy to add or remove parameters. Also we can skip optional parameters easily.


Currying: Partial Apply. We can transform an existing function to return another function when it has less number of parameters, and hardcode sent parameter so that we don't have to send that again. Here is an example:



var multiply=function(a,b){
    var olda=a, oldb=b;
    if(oldb===undefined){
        return function(newb){
            return olda*newb;
        }
    }
}


var multiplyby3 = multiply(3)
multiplyby3(4) //12 


var multiplyby9 = multiply(9)
multiplyby9(4) //36

Immediate Object Initialization

Just like Immediate functions we can declare immediate object initializations as well. 


Example:

({
init:function(){
    console.log('immediate initialization')
}
}).init()

Only problem with this is, most of the minification tools fail to minify such object declarations. 

Tuesday, December 28, 2010

Immediate Functions

Immediate Functions are the function which gets executed as soon as it's defined. For Example:

(function () { 

alert('Im an immediate function');

}());


or

(function () { 

alert('Im an immediate function');

})();


Only difference between above 2 examples is placement of "()", both are valid but JSLint prefers first one.Observe extra parenthesis after function definition and another set of parenthesis covering whole thing. First set of parenthesis after function definition make sure function executed immediately, and second set of parenthesis is needed only when you are not assigning it to an variable name. if you are assigning it to a variable you can omit them, like

var boo = function () { 

return 'Im an immediate function';

}()


Here function gets executed immediately and assigns returning value to a variable "boo".  When you have some server side code returning some data which needs to be kept private from further alterations, we can wrap them in immediate function, and expose only needed part of it by providing methods to do so.

Lazy Function Definition

Lazy Function Definition is a pattern of function definition where a function is not defined properly until you execute it for first time. Assume you have some setup work which you need to do on page load, and you have to do that only once. In such case you can overwrite your function while executing it for first time. 

For example:
Assume that you need a function to return page loaded time, you write a function that get called on page load, and every time you need to refer page loaded time.

var getPageLoadedTime =function (){

var pageLoadedTime = new Date();

getPageLoadedTime=function(){

return pageLoadedTime;

}

}


When you call this function first time, it will set and store pageLoadedTime, and overwrite old function with new one that return the same time on every subsequent calls. This can be very useful when you have to do lot of setting up in your code. Also it can help you in reducing global parameters. 


Callback Functions

A function can be sent as a parameter to another function. The function that is being sent as a parameter to be executed in later stage is called callback functions. The main function that is being executed will call this callback function as needed.In Javascript whenever you call a function, that function get executed in scope of calling function. To execute a function under given scope:

functionName.call(scopeReference, params);

in above example function "functionName" is being executed in scope of "scopeReference".
These kind of callback functions is the heart of EventListening in Javascript. While adding EventListeners it accepts another function as a parameter, that is a callback function that needs to be called while particular event occurs. for example:
document.addEventListener("click", console.log, false);
Here console.log is a callback function, which supposed to be called whenever user click on document (browser window).

Another example of using callback functions are setTimeOut() and setInterval() calls. One thing that needs to be observed here is whenever a function is passed as an argument, function name without parenthesis is passed. because adding parenthesis will execute the function immediately and pass returned object. By removing parenthesis, calling function will get just reference to the callback function.

Functions

In Javascript functions are nothing but Objects. Only difference btw Objects and functions are, function can be called for execution, where as objects cannot. Since they are object they can have there own properties and methods. 

In Javascript function can be defined in four ways. 

1. function declaration:
function boo(){}
these kind of function can be defined in global scope or inside other functions

2. function expression:
var boo=function(){};
When you don't give a name to function it's called anonymous function. Name property of such functions will have empty string ("") in Firefox, Webkit and will be undefined in IE.
3. named function expression:
var boo = function boo(){};
Naming a function expression is important when you wish to get function names to debug your code in debuggers like Firebug etc. And it's also important when you wish to call the function recursively within that.
4. by calling function constructor:
var boo = new Function ('a','b','return a+b');
This way of defining function is as bad as eval(). It needs extra care in escaping quotes. It's better to avoid it.

Sunday, December 26, 2010

Do you know?

1. hasOwnProperty() filter out properties that comes through prototype chain
2. HTMLColletion objects are live queries on DOM. and DOM operations are normally expensive
3. i+=1 is better than i++;
4. Javascript implicitly typecast variables while comparing, to avoid it use === or !== instead of == or !=
5. eval() is evil. Just avoid it
6. Passing strings to setInterval(),setTimeout() and Function() is more or less like eval()


Little known behavior on Javascript.

Most of us know that when we declare variable without using "var" keyword that variable will get defined in global scope and will be available to be called any where in the Javascript program. But look at the following code:

name="Ravi"

function nm(){

    alert(name)

    var name="Kavi";

    alert(name)

}

nm()


When you run this code in a browser you expect to see 2 alerts and one with name "Ravi" and another with name "Kavi". But for your surprise you get "undefined" in the first alert. You know why? This is the unique behavior off Javascript. in your function irrespective of where you use "var" keyword code will get parsed as if you have that variable declared in first line of the function. Hence it's good practice to declare all variables on the top, so that your code looks and works same way. 

Friday, December 24, 2010

Javascript is Object Oriented Language

It might surprise many of the developers, but Javascript script is Object Oriented. Whatever code you write in Javascript you are more or less creating or handling created objects. There are only five primitive datatypes in Javascript which are not objects, they are number, string, boolean, null, and undefined.

So, What is an Object? Just like as it is in other programming languages, an object in Javascript is just a collection of named properties, a list of key-value pairs (almost identical to an associative array in other languages). Some of the properties could be functions (function objects), in which case we call them methods.

Sunday, August 15, 2010

Event Handling

Event in the context of a web page is occurrence of something interesting in page. It can be a click, hover or data load. We can listen to event using handlers. Since all Firefox, Chrome, Opera and Safari implemented core DOM level 2 events, Event handling is similar in all browsers except IE, which still use proprietary event system.

Event handling is bit tricky thing in JavaScript, assume that you click a button in an web page. By clicking that button you will also click container div of button and also the page that contains this button. Deciding which target fire event first is what we describe as Event flow. Different browsers handle event flow differently.

IE kind of event flow called as Event Bubbling, in which Event capturing starts from most specific target and bubbles up till document object.

Say we have an html page with following html code

<html>
<head>
<title> Event Bubbling Example < /title>
</head>
<body>
<div id=”myDiv”> Click Me < /div>
</body>
</html>

Clicking on div, event capturing happens from div -> body -> html -> document flow.

Netscape came up with alternate approach called Event Capturing where it works in opposite way, event get captured in opposite order document -> html -> body -> div.

DOM level 2 events has 3 phases: event capturing, target and event bubbling. Event capturing occurs first, starts with topmost object of the page, and moves towards actual target. Phase 2 is when event reach actual target which is in above case is "div". The final phase is bubbling, which starts from actual target and moves towards topmost document/window object. Ever at-target phase is a different phase all together, but some Browers like Safari, Firefox have "at-target" appended to capturing phase. Hence you can capture event in both the faces.



Please note that IE doesn't support DOM event flow.

Monday, August 9, 2010

Beauty of Javascript

Javascript is the buzz humming around web and internet today. Being able to use javascript extensively is very important for a web dev. be it a simple personal portfolio or complicated application javascript and javascript libraries let you do cool stuff which our predecessors 10 years back, didn't even imagine.

If you look back in history Javascript has developed from "onclick" "onchange" to superior heights. Here is a try to capture some of it's beauty in lines.