Saturday, December 15, 2012

Delegates basics in .NET


Lets try to understand the concept behind delegate using following example -
 public class Program
{
    public delegate object myDelegate(B a);
    public static myDelegate globalDelegate = new myDelegate(someMethod1);
    static void Main(string[] args)
    {
        myDelegate md = new myDelegate(someMethod1);
        md.Invoke(new B());          
        myDelegate md2 = new myDelegate(someMethod2);
        md2.Invoke(new B());          
    }
    static string someMethod2(B b)
    {
        return b.ToString();
    }
    private static string someMethod1(A a)
    {
        return a.ToString();
    }     
}
public static class outer
{
    public static void test()
    {
        Program.globalDelegate.Invoke(new B());
    }
}

 public class A { }
 public class B : A { }


1) Delegate are like function pointers in C.

2) Delegate indicates the signature of callback method. In the  above example i have defined delegate which takes type B as input and returns object. This delegate can be used to create a wrapper(pointer) for any method which takes B(or its base ) type as an argument and returns object(or its derived types).

 3) Its possible to access private method defined in one class using delegate in another class. In above case if you see we have a public delegate object globalDelegate which is pointing to a private method. But we have invoked that method from an outer class using that delegate. It doesn't mean that using delegate we have any security violation for one type to have code that calls another type's private member as long as the delegate  object created by code that has ample accessibility.

4) Covariance and contra-variance in Delegates -
Both c# and CLR allows covariance and contra-variance of reference(and only reference) types when binding a method to a delegate.
Covariance - a method can return a type that is derived from delegates't return type
Contra-variance  - a method can take a parameter that is base of the delegate's parameter type.
In the above code the return type the myDelegate is expecting is object. As per covariance we can return anything derived from object(only reference type), in current case we are returning string.
Moreover if you see the input parameter myDelegate is expecting is of type B. As per Contra-variance we can use this Delegate for anymethod which is expecting any type which is base for type B(current scenario it is A) as input parameter.

5) If you check the IL generate while using delegate, you will find that the delegate we define, compile creates a class out of it, which has 4 methods constructor, Invoke,BeginInvoke and EndInvoke. This class inherits from System.MulticastDelegate which is derived from system.delegate which itself derived from system.Object.

6) All the delegates inherit from MulticastDelegate, hence they inherit all the proerpties methods. There are 3 most important non-public fields which are important to understand -
_target - for static method delegate its null, else its the object reference on which callback method is going to get execute.
_methodPrt-  internal integer which itentifies which method need to execute.
_invocationList - for normal delegates its null, but when we are talking about chain of delegates, then this is the array which hase pointer to every delegate added into chain.
Here is the diagram which shows the different between static and instance level delegate -

7) Combine - We have combine method available in delegate, which can be used to attached multiple delegate and execute them on any event. The combine method makes use of invocationList to keep the list of delegate and execute them one after another.

Sunday, November 25, 2012

.NET basics- introduction to execution model

Metadata -
When we compile code it emits IL and Metadata. Metadata is set of table which contains information of what is defined in modules(types and members) and what module references(imported types and members).

Importance of Metadata -
Removes the dependency of header and library files when compiling. It has all the information of defined types and referenced types.
Metadata field allows an object's field to be serialized into memory block, and deserialized to create the object back.
Metadata allows garbage collector to track the lifetime of objects. Garbage collector can defined the type of the object, and from metadata it can check what all other types using this object.
Metadata is also useful for CLR's code verification process.

IL(Intermediate language) - code the compiler produced as it compiles the source code.
IL is typeless, means add instruction for 32 bit and 64 bit machine will be same.

Metadata and IL both are part of modules. CLR doesn't work with module, it works with assembly.
Assembly is logical grouping of one or more modules. There are different tools available which combines modules and create assembly out of it.

Manifest - IT is another set of metadata tables which describes files that make up assembly, exported types, resources or data files associated with the assembly.

JIT- Just in Time -
Once we write any code compiler will convert that code into IL. But the IL will not directly run on machine. This IL is first compiled into machine language by .NET just in time compiler and then will run.
you can always say the first time execution of any command on any machine will take time, but once its been run, then any further use of the same method will be fast, as instead of compiling the same method again, JIT will take the machine code directly, in order to do so, it maintains some kind of dynamic cache.

Unsafe Code - Code which is allowed to directly access the memory addresses and manipulate bytes at those addresses.

obfuscator utility - IL is very high level language. It is always possible to reverse engineer the code from given IL. If we want to distribute your assembly and dont want anyone to reverse engineer it, then you can use obfuscator utility, which will scramble the names of all private symbols in your assembly's metadata.(It is also not 100% secure, because then also its possible to create source code from IL).

FCL- Framework class libraries - set of assemblies contains thousands of type definition.
CLR - Common language runtime
CTS - Common Type System. CLR is all about types. Types exposes functionality to your application and other types. CLS defines all the types that CLR can understand. It also specifies rules for type visibility and access to the member of a type.
CLS - Common language specification. Minimum set of feature that every CLR language should implement. Because of CLS different languages can talk with each other.

Managed Code can call unmanaged function - using Kernel32.dll and user32.dll, its always possible to call unmanaged component from your managed code.
Unmanaged code can use a managed type- lot many unmanaged code requires you to supply COM component for the code to work. You can always write these COM component in managed language and them use it in unmanaged code.

Tuesday, November 6, 2012

JavaScript Aptitude Test- primitive types


Here are few examples related with primitive type(taken from one of the presentation by Siarhei Barysiuk). It will help us to understand types and their behavior in javascript.

number-
var n1 = 1;
alert(typeof n1);  //number

var n2 = 1.5;
alert(typeof n2);  //number

var n3 = 0100;
alert(typeof n3);  //number
alert(n3);         //64

var n4 = 0xFF;
alert(typeof n4);  //number
alert(n4);         //255

var n5 = 1e1;
alert(typeof n5);  //number
alert(n5);   //10

var n6 = 2e+3;
alert(typeof n6);  //number
alert(n6);   //2000

var n7 = 2e-3;
alert(typeof n7);  //number
alert(n7);   //0.002

var n8 = Infinity;
alert(typeof n8);  //number
alert(n8);   //Infinity

var n9 = 1e309;
alert(typeof n9);  //number
alert(n9);   //Infinity

var n10 = 6/0;
alert(typeof n10); //number
alert(n10);   //Infinity

var n11 = -1*Infinity;
alert(typeof n11); //number
alert(n11);   //-Infinity

var n12 = NaN;
alert(typeof n12); //number
alert(n12);   //NaN

var n13 = 10 * "string";
alert(typeof n13); //number
alert(n13);   //NaN

var n14 = 1 + 1 + NaN;
alert(typeof n14); //number
alert(n14);   //NaN

string-
var s1 = "some string";
alert(typeof s1);  //string

var s2 = 'a';
alert(typeof s2);  //string

var s3 = "10";
alert(typeof s3);  //string

var s41 = "one";
var s42 = "two"
var s43 = s41 + s42;
alert(s43);   //onetwo
var s51 = "10";
alert(typeof s51); //string

var s52 = s51 * 5;
alert(s52);   //50
alert(typeof s52); //number

var s6 = "1";
alert(typeof s6);  //string
alert(++s6);   //2
alert(typeof s6);  //number

var s7 = "some string 1";
var s71 = s7 * 1;
alert(typeof s7);  //string
alert(s71);   //NaN
alert(typeof s71); //number

boolean-
var b1 = false;
alert(typeof b1);  //boolean
var b2 = "some string";
var b21 = !b2;
var b22 = !!b2;
alert(typeof b2);  //string
alert(b21);   //false
alert(typeof b21); //boolean
alert(b22);   //true
alert(typeof b22); //boolean

All values become true when converted to a boolean, with the exception of the six falsy values
var b31 = "";
var b32 = null;
var b33 = false;
var b34 = NaN;
var b35 = undefined;
var b36 = 0;

null-
var nl1 = null;
alert(typeof nl1); //object
alert(nl1);   //null
var nl2 = 1 + null;
alert(nl2);   //1
var nl3 = 1*null;
alert(nl3);   //0

var u2 = 1 + undefined;
alert(u2);   //NaN

var u3 = 1 * undefined;
alert(u3);   //NaN

Arrays-
var a = [1,2,3];
alert(typeof a);   //object
alert(a);   //[1,2,3]
alert(a[0]);   //1
alert(a[5]);   //undefined
a[5] = "some string";
alert(a);   //[1,2,3,undefined,undefined,"some string"]
delete a[2];
alert(a);   //[1,2,undefined,undefined,undefined,"some string"]
delete a[5];
alert(a);   //[1,2,3,undefined,undefined,undefined]

var a2 = [[1,2,3],["string1","string2",3]];
alert(a2[0]);   //[1,2,3]
alert(a2[1]);   //["string1","string2",3]
var a3 = "one";
alert(typeof a3);  //string
alert(a3[0]);   //o
alert(typeof a3[0]);//string
alert(a3[1]);    //n

Monday, November 5, 2012

JQuery Basics - Understanding the insight -5

We will use following html to understand the concepts -

<div class="root">
    <div id="child1" class="div1">
        <span>
        <p class="para">Hi this is 1st para.</p>
        <p class="para">Hi this is 2nd para.</p>
        <p class="para">Hi this is 3rd para.</p>
            </span>
    </div>
    <div id="child2" class="div2">
        <p class="para" id="child2Para1">This is another paragraph1 .</p>
        <p class="para" id="child2Para2">This is another paragraph2 .</p>
        <p class="para" id="child2Para3">This is another paragraph3 .</p>
    </div>
</div>


next() - get the next sibling of matching selector. It helps us to traverse on the same level in the DOM.
Example -$('#child1 .para').next().css("color","blue");
It will apply new css on 2 paragraphs under child1 div.
What if there is no next element available? In that case it returns an empty object, we can always use length property to check if we have any elements available.
We can always use a selector in next() method to select a specific element like this -
$('#child2 .para').next('#child2Para3').css("color","blue");

We also have nextAll() method available which does the similar job for us, but the difference is, next() returns immediate next sibling, whereas nextAll() returns all the siblings. Example -
 $('#child2Para1').next() -- will return you a single object
 $('#child2Para1').nextAll() -- will return you 2 objects.

NOTE - In the above case also $('#child1 .para') itself returns us 3 objects, thus we get 2 objects if we apply next() method on it.

prev() -
It helps us to select the previous sibling of an element. It can be understood as opposite of next, int terms of selected element.
Example -$('#child2Para2').prev().css("color","blue");
it will select element before "child2para2" that is "child2para1".

parent()-
Get the parent of current element in the DOM tree. IT will return immediate parent only. Example -
$('#child2Para1').parent().css("background-color","blue");
It will help us to select the parent of "child2para1", that is div with id "child2" and will set its backgrounf to blue.
What if we want to move higher in the DOM tree, instead of sticking to the immediate parent.
Well for this jquery provides another method "parents()". it returns all the parent object of the current element.
If we use -$('#child2Para1').parents(), then it will return 2 div elements as its parent, 1) child2 and 2) root. It will also return body and html element as its parent. We can pass any selector to parents([selector]) to choose specific parent in the hierarchy.

children()-
Get the child element of current element. We can pass a selector to choose specific child as well. It will return only immediate children, not the descendant ones.
example - $('#child2').children() -  will return 3 elements
$('.root').children() -  will return 2 elements
What if we want to get descendant children as well(along with immediate children)?
Well, we can use find() method which does the similar job for us.
$('.root').find('*') - it will return all the child elements.

closest()-
takes the selector(or element or jquery object) as input and checks the current element or its parent to find the match. It is similar to parent but here are few differences between closest and parent method -
closest start search from current element, whereas parent start search from parent element.
closest return 0 or 1 result whereas parents can return 0 or many results.
closest climb up in the DOM tree, and check for the match, whereas , parents traverse the whole tree first and then filter out the matching results.

siblings()-
get the siblings of given element. Ex.  $('#child2Para2').siblings() returns 3 sibling for given element.

Thursday, October 18, 2012

JQuery Basics - Understanding the insight -4

In this article we will go in the details of jquery selectors. JQuery provides $() or jQuery() to select any element. we can pass any selector in it and it will return a jquery object. If there is nothing available on the DOM with matching selector then an empty jquery object is returned.
$() is same as jQuery().

Context in selector -
When we pass any selector in the $() it start looking for the match starting from the root of DOM, but its always possible to put a context in for the search. For example -

<p> This para is outside DIV</p>
<div id="root">
    <div id="child1" class="div1">
        <p>Hi this is 1st para.</p>
        <p>Hi this is 2nd para.</p>
        <p>Hi this is 3rd para.</p>
    </div>  
</div>

In the above example say if we want to have a functionality where if i click on any div element, every paragraph in it should get background as red. If i use the following script -

$(document).ready(function(){
    jQuery("div").click(function(){
        $('p').css("background","blue");
    });
});
It will change the background of every paragraph, but its possible to limit the scope of click only to those paragraphs which are within div element like this -

$(document).ready(function(){
    jQuery("div").click(function(){
        $('p',$(this)).css("background","blue");
    });
});

what will happend in the following scenario -
<p> This para is outside DIV</p>

<div class="root">
    <div id="child1" class="div1">
        <p>Hi this is 1st para.</p>
        <p>Hi this is 2nd para.</p>
        <p>Hi this is 3rd para.</p>
    </div>
    <div id="child2" class="div2">
        <p id="child2Para1">This is another paragraph1 .</p>
        <p id="child2Para2">This is another paragraph2 .</p>
        <p id="child2Para3">This is another paragraph3 .</p>
    </div>
</div>

Now if we execute following script -$('p',$(this)).css("background","blue"); 1st it will change the background of the div we clicked and then it will bubble up to root div and will change the background of every paragraph(including those available in other child as well) in it. If you want to verify it, attach a debugger and check the value of $(this)[0], first run will have its value as the child div and then it will be root div.

The same functionality can also be achieved in the following way -

$(this).find('p').css("background","blue");
putting context in $() does the same thing that find() does. Infect it internally calls find method to do the same thing, hence directly using find() will be faster then using context in selector.

Working With Plain JavaScript Objects-
If we pass any javascript object in $() then it converts it into a jquery object(which is an array).  These are the methods available in jquery object -.data(),.prop(),.bind(), .unbind(), .trigger() and .triggerHandler().

    var localObj = {"key1":"value1", "key2":"value2"};
    var $jqueryObj = $(localObj); // its jquery object
    alert($jqueryObj.prop("key1")); //alerts value1,
    $jqueryObj.prop('key3','value3'); // it adds new property to the object.
.prop() helps us to add new value in the object, but it doesn't mean that original object will also get the new value, that is because once we pass javascript object in $() it creates a copy of it and wraps it into new jquery object.

Saturday, October 13, 2012

JQuery Basics - Understand the insight -3

JQuery provides different  ways to remove any element or its content from the DOM, we will do comparative study to understand the different between those.

Empty() - Remove all child nodes of the set of matched elements from the DOM.
It removes the content of the selector, NOT the node itself.  For example -
<div class="div1">Div1</div>
<div class="div2">Div2</div>
$(".div1").empty();
It will result in following html -

<div class="div1"></div>
<div class="div2">Div2</div>

If we had any child/nested element in it, then those would also been removed.

Remove() -Remove the set of matched elements from the DOM
It removes the complete element itself.
<div class="div1">Div1</div>
<div class="div2">Div2</div>
$(".div1").remove();
It will result in following html -

<div class="div2">Div2</div>
 
Detach() - Remove the set of matched elements from the DOM
detach is very much similar to remove(), except detach keeps all the jquery data like events subscribed, so that once we add this element again with DOM, all that data can be associate with this node again.

JQuery Events- Understand the insight - 2

JQuery provides different methods to attach an event to any element. All those method does the same thing but are different in some aspects like how the event get attached to an element and how does it get fired once an actions take place.
Lets try to understand all the methods provided by JQuery and see how do they differ from each other.

Here is the Html code we will use for all the jquery examples -
<div id="root">
    <div id="child1">
        <p>Hi this is para.</p>
    </div>
    <div id="child2">
        <p id="child2Para">This is another paragraph.</p>
    </div>
    <div class="EmptyDiv">
        Empty Div
    </div>
</div>

Bind() - Attach a handler to an event for the elements. When we use Bind method, the JQuery traverse the whole DOM tree and check if the selector matches, then attach the event with the element. When the action happens(click), the event get fired from the element directly, and bubbles up. 
We can attach multiple events also. Here is the example -
 $(document).ready(function(){
    $("#child2").bind('click',function(){
        alert('child 2 clicked');
    });
});
If we click on child2, then it will alert "child 2 clicked". Following example shows how to attach multiple events -
$(document).ready(function(){
    $("#child2").bind({'click':function(){
        alert('child 2 clicked');
    }, mouseenter: function() {
        alert('Mouse enter to child2');
    }});
});
If there are multiple events that need to be fired on same action, then they will be fired in the sequence of subscription.
Drawback- In this case the subscription can be little expensive for large DOM structure, as the Jquery traverse the whole DOM tree and attaches the event to the element. 

live() - Attach an event handler for all elements which match the current selector, now and in the future.
In case of Bind the handler get attached to the element itself, but in case of live the handler get attached to the document object.
Here is example which demonstrate the behavior -
$(document).ready(function(){
    $("p").live({'click':function(){
        alert('paragraph clicked');
        $(this).after("New Paragraph
");
    }});
});
In the above code if you click on paragraph it will append new paragraph in the page. The new paragraph will also have this event attached. If you replace the live with bind in above code you wont find the event attached with the newly create paragraphs.
Drawback- live() method is no longer recommended.  Because it have performance and chaining related issues. As the live event get attached to document object by default(because no context is mentioned), thus once we click on any element, then the javascript will traverse whole DOM tree to find that element and execute the handler

delegate()- Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements. It is very much similar to the live() function, except in this case the event get attached to the element(like Bind()) not with the document object.  So the performance hit we get in case of live() wont be applicable in this case.
The above code can be re-written using delegate in the following way -
$(document).ready(function(){
    $("body").delegate("p",{'click':function(){
        alert('paragraph clicked');  
        $(this).after("New Paragraph
");    
    }});
    $("body").delegate("div",{'click': function(){
        alert('div clicked');
    }});
});
Drawback - The drawbacks are very much similar to the one mentioned in Bind, that is if the DOM tree is big then while subscription we might face some performance hit.


On() - Attach an event handler function for one or more events to the selected elements.
It is the combination of delegate and Bind and most recommended event subscription method provided by Jquery. If we pass the selector in the on function then it behave like delegate, and if we skip it, it works like Bind() method. Here are the example -
$(document).ready(function(){
    $("body").on("click", "p", function(){
        alert('paragraph clicked');
        $(this).after("New Paragraph
");
    });
});
Above code works similar to the delegate, and if we remove the "p" as second parameter it will behave like Bind().

Stop Bubbling of Event-
you can return false from the event handler to stop its propogation to the parent elements. Once we do it, it internally calls event.stopPropogation().

JQuery Basics- Understand the insight -1

Lets start understanding basics of JQuery. The syntax if JQuery can be found on its home page or in anyother book, but here we will understand how those APIs are working on top of the JavaScript API. JQuery is built upon JavaScript only. IT wraps the javascript functions in its own wrapper and provide user a sophisticated way of using javascript. Lets start understanding the APIs and how those are different from JavaScript.

$(document).ready Vs window.onload -
There difference between two functions that is the $(document).ready is very much specific to JQuery but the window.onload is JavaScript specific. moreover window.onload waits until all the resources have been loaded, whereas the $(document).ready waits until the DOM is loaded, it wont wait for other resources to load. Here is the code snippet which shows how to use this API -

    $(document).ready(function(){
        alert("Jquery Ready");
    });
    window.onload = windowLoad;
    function windowLoad(){
        alert("Window loaded");
    }
In order to see the difference between these 2, try to load a heavy image and check which event get fired first.

$(this) Vs this -
when we wrap this in the $()then it get converted into JQuery object. Using this we can execute the jquery methods on this object. Internally whenever we put any object inside $(), JQuery converts it into an array, and if we know there is just a single object in it, then we can directly access it using indexer, which means -
$(this)[0] == this will return true.

I ll consider following HTML for all preceding examples -

<div id="root">
    <div id="child1">
        <p>Hi this is para.</p>
    </div>
    <div id="child2">
        <p id="child2Para">This is another paragraph.</p>
    </div>
    <div class="EmptyDiv">
        Empty Div
    </div>
</div>

JQuery Selectors- $() allows you to select element and work on them. Internally its calls different JavaScript APIs like getElementById, ByName etc. to fetch the actual element. But all that dirty code is hidden from user and JQuery have provided really an awesome wrapper to us.
Here are few examples of different kind of selectors available. There are many more ways to select elements in JQuery, but here very basic tricks are covered-
All selectors - "*"
Find every element (including head, body, etc) in the document.
//All selector
$("*").css("background","yellow"); // sets background of all elements to yellow
//ID selection
$("#child2").css("border","5px solid"); // sets the border of element with id child2. It is equivalent to document.getElementById method in JavaScript.
//Class selection
$(".EmptyDiv").css("border","5px solid blue"); // sets the border of (all the)element(s) with class EmptyDiv.
//Element selection
$("p").css("background","blue"); // Sets the background for all paragraphs
//Multiple selection
$("#child1, .EmptyDiv").css("background","green"); // selects multiple element/class/Ids etc. to be worked on
//Hierarchy selection
$("div p").css("border","2px solid red"); // sets border of all paragraph inside every div.
$("#child2 p").css("background","orange"); // Sets background of paragraph inside element with Id child2

width() Vs css('width') -
In JQuery you can access width/height of any element in 2 ways -
    alert($("#child1").width()); // number
    alert($("#child1").css('width')); // number px
The only difference is the return type. width() function returns the width as number, which can be used in any other manupulation if required, whereas the .css('width') returns the width with px as unit in single string, which can be used for further assignment but not in any mathematical manupulations.

HTML() vs innerHtml() -
JQuery Html() method can be used to get any html content of any element(can be selected by jquery selectors).This method internally calls innerHtml javascript function. It is safe to call html() rather then innerhtml(), because if you are calling html() on an element which does not exist, this function will return you undefined object, but the innerhtml will thrown a javascript error. In other words, JQuery have wrapped innerHtml with html() function with proper error handling.

Thursday, October 11, 2012

Cookies in JavaScript

Cookie is one of the most important concept in web design which help you to maintain some state in a stateless environment. Of course there are different views with respect to security of cookie, but it doesn't mean we shouldn't use it. While using we need to make sure that we don't have any sensitive data in the cookie. because its very easy for any hacker to read it from your browser.
Lets start understanding how can we play with cookies in JavaScript, but before that lets have a look at the structure of cookie.If you open browser and check how cookie look like, you will find following content in it-

Name: send
Content: 1342885667964
Host: 107.22.149.124 (Or SomeTimes- Domain : .abc.com)
Path: /
Send For: Any type of connection
Expires: Never Or SomeDate(Thursday, July 20, 2017 9:17:47 PM)

You can use JavaScript to create cookies by using the document.cookie property.
Following code shows how can we set cookie using JavaScript -

    var key = "Cookie-Key";
    var val = "Cookie-Value";
    var myCookie = key + "=" + val;
    document.cookie = myCookie;

We can always add expire date to the cookie like this -

    var key = "Cookie-Key1";
    var val = "Cookie-Value";
    var myCookie = key + "=" + val;
    var date = new Date();
    var numOfMilisecond = 10000;
    date.setTime(date.getTime()+numOfMilisecond)
    var expireDate = date.toGMTString();

    document.cookie = myCookie + ";expires=" + expireDate;

If we execute this code then cookie saved is -

Name: Cookie-Key1
Content: Cookie-Value
Host: localhost
Path: /TestApp/
Send For: Any type of connection
Expires: Thursday, October 11, 2012 10:09:03 PM

In the above code we can get the current date using getDate() function and can add the number of millisecond in it. For example if we want the cookie for 24 hour then the number will be adding is -
24 * 60 * 60 * 1000 = 86400000.
Once we have the current date then we convert it into GMT time and set it into cookie.

If you see currently the cookie is been set for this virtual directory only, but what if we want it ti be for the whole domain. We can do it by explicitly setting the path. Here is the code which demonstrate how to set the path property in the cookie -

    var key = "Cookie-Key3";
    var val = "Cookie-Value";
    var myCookie = key + "=" + val;

    var date = new Date();
    var numOfMilisecond = 10000;
    date.setTime(date.getTime()+numOfMilisecond)
    var expireDate = date.toGMTString();
    var path = ";path=/";

    var myCookie = key + "=" + val + ";expires=" + expireDate + path;
    document.cookie = myCookie + ";expires=" + expireDate;

Once you browse this page you will find the cookie properties as following -

Name: Cookie-Key2
Content: Cookie-Value
Host: localhost
Path: /
Send For: Any type of connection
Expires: Thursday, October 11, 2012 10:20:25 PM

We can always set the domain by using domain = images.mydomain. We can not set the domain out of the domain from where is the content is been served. for example if the page is coming from microsoft.com i can not set the domain as amazon.com.

We can use the "secure" property of cookie to transmit the cookie on secure connection. By setting secure flag in a cookie depicts that the cookie will be sent only when the connection uses SSL, such as an HTTPS connection. in the above code append "secure" in the cookie like this -
var myCookie = key + "=" + val + ";expires=" + expireDate + path + domain + ";secure";

After this if you analyze the cookie then you will find the property "Send For" is changed -
Send For: Encrypted connections only

Reading cookie-
If we want to read existing cookie in JavaScript then we can use the document.cookie to read the cookie. It will return ";" separated cookies.
var cookies = document.cookie.split(";");

Deleting Cookie -
There is not way provided by JavaScript by which you can delete a cookie. If we want to remove any cookie we can always set it expire time as sometime in past.

Saturday, October 6, 2012

Currying in JavaScript

Currying or partial function are very important concepts in functional programming. Most of the time these terms are used interchangeably, but few experts mention slight difference between them.
function returing object - Constructor
object returning object Lets try to understand the concept behind Curry and partial function.

Partial function-
Lets take a simple example of add method.

function add(a,b){
   return a+b;
}
alert(add(5,6)); //11
Now i want to modify the above function, so that i can execute it in the following manner -
add(5,6); //11
add(5)(6); //11
var a = add(5);
a(4); // 9
a(3); //8

If we execute add(5) in the above mentioned definition, then it will return NaN, as b is undefined.
Now if see the requirement properly add(5) should return a function which can take another parameter and finally return the result by adding the first value. lets try to write that function -


function add(a,b){
    if(typeof b == 'undefined'){
        return function(c){
            return a+c;
        };
    }
   return a+b;
}
var b = add(5);
alert(b(3)); //8
alert(add(3,4)); //7
If you see the above example, its returning another function if 2nd parameter is not passed. Moreover the inner function retains the value of passed parameter in the form of closure.

It will be very difficult to scale this functionality, because we will have to write this kind of logic for every function. Say in future another function(multiply) comes and we have to write similar functionality for that as well. So its always possible to create another function say createPartial which an act as a generic solution for this. Have a look-


function partial(fn) {
    var aps = Array.prototype.slice,
            args = aps.call( arguments, 1 );
    return function() {
        return fn.apply( this, args.concat(aps.call( arguments )) );
    };
}
function add( a, b ) {
    return a + b;
}
function multiply(a,b){
    return a*b;
}
var add1 = partial( add, 1 );
add1( 2 );
var multi2 = partial(multiply,3);
multi2(4);

In the above example we have created a reusable partial function, which is used to create a partial function for add as well as multiply.

Curry-
Currying can be described as transforming a function of N arguments in such a way that it can be called as a chain of N functions each with a single argument.
JavaScript does not provide inbuilt Curry function but its always possible to make our own.

function curry(/* n,*/ fn /*, args...*/) {
    var n,
            aps = Array.prototype.slice,
            orig_args = aps.call( arguments, 1 );

    if ( typeof fn === 'number' ) {
        n = fn;
        fn = orig_args.shift();
    } else {
        n = fn.length;
    }
    return function() {
        var args = orig_args.concat( aps.call( arguments ) );

        return args.length < n
                ? curry.apply( this, [ n, fn ].concat( args ) )
                : fn.apply( this, args );
    };
}
var i = 0;
function a( x, y, z ) {
    console.log( ++i + ': ' + x + ' and ' + y + ' or ' + z );
};
a( 'x', 'y', 'z' );     // "1: x and y or z"
var b = curry( a );
b();                    // nothing logged, `a` not invoked ------------(1)
b( 'x' );               // nothing logged, `a` not invoked------------(2)
b( 'x' )( 'y' )( 'z' ); // "2: x and y or z" --------------------------(3)
b( 'x', 'y', 'z' );     // "3: x and y or z"  --------------------------(4)



Lets try to understand the above code. Once we call var b = curry(a); the following function get assigned to b-

 return function() {
        var args = orig_args.concat( aps.call( arguments ) );
        return args.length < n
                ? curry.apply( this, [ n, fn ].concat( args ) )
                : fn.apply( this, args );
    };
If you see here we have passed orig_args in the form of closure, which means the originally passed arguments are intact. In this function we check if the arguments are sufficient or not. In our case the n(expected number of arguments) is 3. If it is sufficient then the function will execute with the parameter passed. If we have not got expected number of inputs the function returns another function along with the parameter passed till now.
In the Above code we have used curry function again and passed n,fn and other arguments. If you see in the Curry function we have checked if fn==number, this is to check if the Curry function is been called in following manner-
curry( expected number of args , function definition , other arguments)
If the format is so, then we treat the first argument as the number of args expected, and use the shift property to get the function definition.
Moreover If you see we have called slice method of Array on argument object that is because arguments is array-like, it is not an array. This means that while it has a .length property and numeric indices, it doesn't have the normal Array.concat or .slice methods. In order to convert the arguments object into an array, the native Array.slice method (Array.prototype.slice) is invoked as if it existed on the arguments object via call.
lets try to see the usecases -
1-b();-> Here is the flow what happens -

1) as number of required args is 3 and we didnt pass any args this call to curry.apply( this, [ n, fn ].concat(args))
2) Call Curry function with arguments as 3 and function definition
If you see the if block fn == 'number' is true , thus n = 3 will be assigned and the function definition is assigned to fn using shift method.If you see orig_args will be empty as there is no arguments left.
With this state the function is returned -
 return function() {
        var args = orig_args.concat( aps.call(arguments) );
        return args.length < n
                ? curry.apply( this, [ n, fn ].concat( args ) )
                : fn.apply( this, args );
    };

There are 4 closures - orig_args, aps,fn and n.

2. b('x')-> The flow will be identical to what is mentioned above except this time orig_args will contain x as one of the parameter passed and this value will be passed to the function in the form of closure.

3. b('x')('y')('z') -> b('x') retuns a function which we mentioned above and in this case that function get execute with input parameter as 'y', which again returns another function(which has values x and y in its orig_args) and then finally once we execute it with input as z, it has all the required parameter in it, and hence give the expected output.

4. n('x','y','z') -> this is very straight forward and returns the output as expected.

Partial function Vs Curry -
Most of the times these terms are used interchangeably, but few experts consider them different in the following way -
Unlike partial application, which invokes the partially applied function whether all of its arguments have been satisfied or not, a curried function will only be invoked once all of its arguments have been satisfied, otherwise a function will be returned.
Example-
var a1 = partial(add,1);
var a2 = curry(add,1);
a1(); --> NaN
a2() --> function

Ref - http://msdn.microsoft.com/en-us/magazine/gg575560.aspx


Saturday, September 22, 2012

Closures in JavaScript

Closures is a kind of object which combines 2 things - a function and the environment in which this function is been created. In simple words when we define an inner function, and that inner function uses the any variable defined outside(say in its outer function), then it is known as closure. Because even if the outer function returns then also this local variable is still in use by the inner function.
Lets understand it step by step using examples -

    function Outer(){
        var local = 1;
        return function(){
            return local;
        }
    }
    var outVar = Outer();
    alert(outVar());
In the above example if you see once the outVar is defined, the Outer function get returns. Then also the value local is available via inner anonymous function, This is simplest example of closure.

check the following scenario -


  var outVar ;
    function Outer(){
        var local = 1;
        outVar =  function(){
            return local;
        }
    }
    alert(typeof outVar);//undefined
    Outer();
    alert(typeof outVar); //function
    alert(outVar()); //1
Above example is very much similar to the 1st one.


Lets complicate the above example a little bit -

    var outVar ;
    function Outer(){
        var local = 1;
        outVar =  function(){
            return local;
        }
        local = 2;
    }   
    Outer();  
    alert(outVar()); //2
If you notice in above example, after assignment we have modified the value of local to 2, and once you call the closure, it alerts 2 not 1. It means the inner function is actually using the same local object of outer function, it didn't create a local copy of it.
Lets check one more example to understand it little deeper -

    var outVar1,outVar2 ;
    function Outer(){
        var local = 1;
        return function(){
            local++;
            return local;
        }
    }
    outVar1 = Outer();
    outVar2 = Outer();
    outVar1();
    outVar2();
    alert(outVar1());//--1
    alert(outVar2());//--2
In the above example, what you think will be the alert in statement 1 and 2, as both outVar1 and 2 are assigned the same inner function. Well the answer is both of them will alert 3, as they have their own copy of local variable(because local is actually a local variable of outer function).

Analyze the following code -

    function make(){
        var i;
        var a=[];
        for(i=0;i<3 i="i" p="p">            a[i] = function(){
                return i;
            }
        }
        return a;
    }
    var funcs = make();
    alert(funcs[0]()); //--1
    alert(funcs[1]()); //--2
    alert(funcs[2]()); //--3
What you think will be the output of above code?
At first you will think it might be 1,2,3 ....but actually it will alert 3,3,3. This is because the inner function get bound with the local variable i, and once we assign it to array, it actually got assigned( not evaluated or not executed). Thus once we execute it, it actually refer to same i from its outer function, and as its state got changed to 3, thus it alerts 3.
Now how can we fix this problem? Here is the fix -

function make(){
        var i;
        var a=[];
        for(i=0;i<3 i="i" p="p">            a[i] = (function(input){
                return function(){
                    return input;
                };
            })(i);
        }
        return a;
    }
    var funcs = make();
    alert(funcs[0]());
    alert(funcs[1]());
    alert(funcs[2]());
If analyze the code we have created another function which takes input as i, and then pass it further down to another function. Now the inner function or the closure is actually not connected to i directly.
Above code is very important to understand, we see application of closure in our daily javascript coding. Here is an example on the same concept where we are using the same concept -


for(i=0;i<3 i="i" p="p">            document.getElementById('btn'+i).onclick = function(){
                alert(i);
            }
        }
it will have the same issue, it will alert only 3. Here is the corrected version -

 document.getElementById('btn'+i).onclick = (function(input){
                return function(){
                    alert(input);
                }
            })(i);






JavaScript- Basic Concepts

Java Script is not a subset of Java, its completely different language. It is scripting language. JS programs are delivered as source code, it is never compiled(like any other language). It also provide loose typing, although its always preferred to have strong compiler check while you program. There are no classes in JS, there are only objects. IT also supports lambda, which means function as first class member. There is not linker in JavaScript thus all variables are combined in common namespace(global).

JS has following types of values -
Number
String
Boolean
Objects
null
undefined

Number -
There is only one Number type in JS, no integer.
it is represented as 64 bit floating point also known as IEEE -754 (double)
Decimal arithmetic is not good in JS, which means
0.1 + 0.2 == 0.3 -> false. Thus while critical operation always convert the number to integer and then apply arithmatic.
Special type named as NaN(Not A Number).
It is result of undefined ot erroneous operations. Any operation having NaN as input will result as NaN. NaN is not equal to anything, not even equal to Itself. But if we check the type of NaN, it is Number.

Number function - Number(value) -Converts value into number.  It produces NaN if it has a problem. It similar to + prefix operator.
+"42" -> 42
Number("42") -> 42

parseInt(value,10) - specialized in converting values into integers. It stops at first non-digit character. The radix value is required.
parseint("08") - > 0 treated as octal
parseInt("08",10) -> 8

String -
It is sequence of 0 or more 16-bit characters. There is no separate character type in JS. String in JS are immutable. String literals can use single or double quotes, both are same.
String function - String(value), convert value into string(say number).

Boolean - true and false
Boolean function - Boolean(value), convert value to boolean.
returns false for falsy values and true for truthy values.
Here are the falsy values - false, null, undefined, "", 0 , NaN
All other values are truthy, including all objects even "0" and "false"(as string values)

null- value that is nothing.
undefined - default value of variable.

EVERYTHIN ELSE IN JS IS OBJECTS.

Friday, September 21, 2012

JavaScript Tips and Tricks-8

Importance of constructor in javascript-
Check the following code -
        function Circle(radius){
            this.radius = radius;
            this.area = function(){
                return this.radius * this.radius * Math.PI;
            }
        }
       var c1 = new Circle(5);
        var c2 = {};
        Circle.call(c2,5);
       alert(c1 instanceof Circle); //true --1
        alert(c2 instanceof Circle); //false --2
        alert(c1.constructor == Circle); //true --3
        alert(c2.constructor == Circle); // false --4
Above code depict the difference between using "new" operator and calling call method on class to create new object. As you can check the output of statement 1,2,3 and 4.
"new" is equivalent to following 4 statements -
        var c2 = {};
        c2.constructor = Circle;
        c2.__proto__ = Circle.prototype;
        Circle.apply(c2,[5]);
Thus if we use "new" statement to create new object we get proper inheritance.

__proto__ Vs prototype-
__proto__ - Runtime uses to look at the parent object to resolve the properties, we can say it to be runtime reference to the parent object. All the object has __proto__ property.
prototype - It is special property of function and function only, to which "new" operator uses to copy onto the __proto__. It can be considered as template. All the function has prototype.


Function as return value-
Its always possible to return function as an object. lets see what happens in following example -
        function func1(param1){
            var counter = 0;
            return function(param2){
                return param2 + '-' + param1;
            }
        }
        var myvar1 = func1('firstcall');
        var myvar2 = func1('firstcall');;
        alert(myvar2 === myvar1); // false
If we assign the same returned function to myvar1 and myvar2, still its not equal because its 2 different instances of function.

Importance of non-blocking calls in JavaScript

In javascript there is only one thread. The same thread is responsible for running your code as well as updating the UI. Think about a server call which takes around 5 sec to come back. If we make such server call and wait for its response then the UI will be stuck for 5 sec. In order to avoid such circumstances we generally use callback methods. lets take the following example -

         function Greeter(s){
               this.salutation = s;
         }
         function Server(){}
              Server.prototype.getUser = function(fn){
              // Make a service call and fetch the user details
              fn.apply(this,['user']);
        }
        Greeter.prototype.greet = function(name){
            alert(this.salutation + '-' + name);
        }
        var greeter = new Greeter('Salutation');
        var server = new Server();

        server.getUser(greeter.greet); // undefined - User ----1
        server.getUser(
                function(name){
                    greeter.greet(name); // Salutation - User ----2
                }
        );
In the above example we are making a server call and passing a callback method, once the call is complete we want to greet the user. With the 1st attempt of passing the call back function it alerts 'undefined - User', that is because the 'this' got changes. In this 1st case once we call greet, it gets call on window not on greet, thus it try to get this.salutation(which becomes window.salutation) and returns undefined.  It happens because we are not calling the function in this line -  server.getUser(greeter.greet); there is no parenthesis here, we are just passing a variable name here, which is pointing at a function. The actual call is made from fn.apply (inside Server.getUser), where this becomes window and thus gives unexpected result.
In the 2nd case we are passing a function which eventually calls  greeter.greet() function, here this object is greeter which is never lost because we are actually calling it here. and thus we get expected result.

The above code is not very much scalable, Which means we will need to do the same thing for every callback function. We can make this code more generic like this -

function bind(funcThis,fn){
        return function(){
            return fn.apply(funcThis,arguments);
        }
    }
and then use this to bind greeter with greet -server.getUser(bind(greeter,greeter.greet));

Browser has a queue of events/tasks that needs to be done ordered by timestamp. If we have a call to server and an associated call back function with it, then the callback event/function actually get en-queued into the browser queue at the head of the queue. In other words the callback function takes the priority in the queue.
Here is the pseudo code which shows how browser behaves -
while(true){
   var event = waitForEvent();
   try{
        event();
   }catch(e){}
   redrawDOM();
}

Browser keeps waiting until next event comes and once it comes, it executes it.

Sunday, September 16, 2012

JavaScript Tips and Tricks - 7

Avoid eval in javascript -
var string1 = "var num1 = 1; alert(num1);";
var string2 = "var num2 = 2; alert(num2);";
var string3 = "var num3 = 3; alert(num3);";
eval(string1);//--1
new Function(string2)(); // --2
(function(){
    eval(string3); // --3
}());
alert(typeof num1); //--4
alert(typeof num2); // --5
alert(typeof num3); // --6
Output-
(1) - 1
(2) - 2
(3) - 3
(4) - number
(5) - undefined
(6) - undefined
NOTE - eval interfere with the scope chain,if the scope where eval is called, is global then it will make the variable Global. To overcome such problem we can wrap eval in an immediate function.eval can also access and modify a variable in its outer scope,whereas function cannot.

Arrays - use [] instead of new Array() -
var a = [3];
alert(a.length); // --1
alert(a[0]); // --2
//---
var b = new Array(3);
alert(b.length); // --3
alert(b[0]); // --4
 //--
var c = [2.34]
alert(c[0]); // -- 5

output -
 (1) -1
 (2) - 3
 (3) - 3
 (4) - undefined
 (5) - 2.34
If we use new Array() to construct a new array and pass a integer number to it, it takes 1st parameter as its length, in every other case it behaves differently. Thus its always recommended to avoid new Array and use [] to construct an Array.

Wrapper Objects -
In javascript for primitive types number,string and boolean we have wrapper objects Number(), String() and Boolean() available.
example -
var a = 100;
typeof(a); --> number
var objA = new Number(100);
typeof(objA); --> object
There are few methods available on object, but if we execute them on primitive as well, it works -
var s = "hello";
s.toUpperCase();
It is because of primitive can act as an object when needed(similar to auto boxing).But it does not mean that primitive variable will itself converted into object and will remain object. For that particular function/method it will get convert to object and then back to primitive. Here is example -
var s = "hello";
alert(s.toUpperCase()); -- > HELLO
s.newmethod = function() {
    alert('new method');
}
s.newmethod(); --> ERROR


JavaScript Aptitude Test


Ques - Write partial function in javascript. Here is the expected behavior of that function -
function add(param1,param2){
    return param1 + param2;
}
add.apply(null,[5,4]); // returns 9

now modify the add function so that we can pass the parameter 1 by 1, i.e.-
add(5)(4) ; // 9

Ans -
function add(x,y){
     if(typeof(x) === 'undefined'){
           return function(y){
                return x+y;
           }
     }
     return x + y;
}

Ques - Write a function namespace() which can create a namespace hierarchy for you-
MYAPP.namspace('module1,module2,module3'); should create a namespace named as MYAPP.module1.module2.module3.
Ans -
Generally we can directly create namespace like this -
MYAPP = {};
the issue is, whats if this name was already exist, then by writing this statement, we will override the existing function. So here is the right statement -
MYAPP = MYAPP || {};
Here is small code which creates a namespace -

namespace = function (ns_string){
    var parts = ns_string.split('.');
    var root = {};
    if(parts.length>0){
        root = this[parts[0]] || this;
    }
    for(var i=0;i        if(typeof (root[parts[i]]) === 'undefined') {
            root[parts[i]] = {};
        }
            root = root[parts[i]];       
    }
    return root;
}
namespace('global.MSSB.WebFramework.Coreservice');
alert(global.MSSB.WebFramework.Coreservice);



Ques - What will be the output of following function-
var myvar = function() {
    alert('my old var');
    myvar= function() {
        alert('my new var');
    }
}
var anotherVar = myvar;
anotherVar(); // --1
anotherVar();// --2
myvar();// --3
myvar();// --4
anotherVar();// --5
anotherVar();// --6
Ans -myvar defines a function, which while execution define the myvar again, and thus overrides the original definition of myvar. But while assignment of myvar to myanotherVar, the old definition only gets copied, and every time the old function get executed. Lets understand it by looking at the output -
(1) - my old var
(2) - my old var
(3) - my new var
(4) - my new var
(5) - my old var
(6) - my old var
 If you check, anotherVar alerts the old definition whereas myvar alerts the new definition, because once the myvar got executed, its original definition got overwritten by the new definition.


Encapsulation in JavaScript

Public Memebers -
 Lets see the following example -
 function Person(){
    this.name = 'name1';  
}

var p = new Person();
alert(p.name);

Private memeber -
Lets see the following example -
function Person(){
    var name = 'name1';
    this.getname = function(){
        return name;
    }
}
var p = new Person();
alert(p.getname()); // name1
alert(p.name); // undefined
Here the property name is private and the method getname is public, we also call it a Privileged Method, which means a public method to access private variables.

Lets see little complex example -
function Person(){
    var name = 'name1';
    this.getname = function(){
        return name;
    }
    var detail = {
        salary:1000,
        address : 'abcd',
        company:'Company1'
    }
    this.getdetails = function() {
        return detail;
    }
}
var p = new Person();
var detail = p.getdetails();
detail.company = 'new company';
In the above example even if the detail is private, but still because of getdetail method, the original object of detail get return. In order to avoid such circumstances, create a copy of the object and then return.
Or else create another object with only required detail, for example if you dont want to give the detail of salary, create another object with address and company detail in it. This is also known is Principle Of Least Authority(POLA).

JavaScript Tips and Tricks - 6

Implicit Vs Explicit Global Variable-
We all know that if we don't write var keyword, JavaScript will define the variable globally.
var myglobalVar = '';
(function (){
   anotherGlobalVar = '';
})();
typeof(myglobalVar); // string
typeof(anotherGlobalVar); // string
In the above example both myglobalVar and anotherGlobalVar are global and thus are available in the whole javascript.The "anotherGlobalVar" is also called as implied global variable.
The implied global variables are technically not real variables, the are properties of global object. Properties can be deleted with delete operator whereas variables can not and that is why we can delete the peoperty anotherGlobalVar but not myglobalVar.
which means -
delete myglobalVar; // false
delete anotherGlobalVar; //true

There are other ways where we can create implied global variables, one of them is chain of assignment.
Here is example -
function(){
    var a = b = 0;
}
In the above example variable a is local, whereas b is global.

Variable Hoisting -
JavaScript enables you to have multiple var statements anywhere in a function, and they all act as if the variables were declared at the top of the function. This behavior is known as hoisting. Sometimes it creates problem. lets take an example -
var myglobalVar = 'global';
(function (){
    alert(myglobalVar); //--1
  var myglobalVar = 'local';
  alert(myglobalVar); // --2
})();
In the above example what do you think the output will be? 1- global and 2- local, right? -- NO
the output is undefined and local. myglobalVar is declared locally. Even if it is declared after alert, then also JavaScript consider this as local and for this scope of the function it will be local. Thus the first alert gives undefined and another one gives local as output.

Function Hoisting  -
When using function declaration, the definition of the function is also get hoisted, not only its declaration. The function can be defined either by function declaration or by function expression.
function expression -
function a() {};
function declaration -
var a = function (){};

Both of these will show different behaviors because of hoisting. Consider following example-
function func1(){
    alert('global func1');
}
function func2(){
    alert('global func2');
}
function func3(){
    alert(typeof(func1)); // function
    alert(typeof(func2)); //undefined
    func1(); //local func1
    func2(); // Error - func2 undefined

    function func1(){
        alert('local func1');
    }
    var func2 = function(){
        alert('local func2');
    }
}
func3();

In the given example func1 get hoisted along with its definition, but func2, its just declaration which get hoisted.

Function Invocation -
There are four ways to call a function:
Function form - Value of "this" is global object.
functionObject(arguments)

Method form- Value of "this" is set to "thisObject", object which this method defined.
thisObject.methodName(arguments)
thisObject["methodName"](arguments)

Constructor form- A new object is created and assigned to "this".
new FunctionValue(arguments)

Apply form- Value of "this" object will be "thisObject", an explicitly passed value.
functionObject.apply(thisObject,[arguments])
functionObject.call(thisObject,arguments)

Sunday, September 9, 2012

Method Overloading in JavaScript

We are all aware of method overloading as a concept, Which states we can have same function name with different arguments. Lets see how can we achieve it in JavaScript.
Before starting on overloading , lets see how length property works on function, because we will need to use that property while building overloading -
function myfunc1(){}
function myfunc2(arg1){}
function myfunc3(arg1,arg2){}
alert(myfunc1.length); --> 0
alert(myfunc2.length); --> 1
alert(myfunc3.length); --> 2

using length property we can identify how many arguments are passed to the function.

Now let try to implement overloading
function addMethod(object,name,fn){
    var old = object[name];
    object[name] = function() {
        if(fn.length == arguments.length) {
            fn.apply(object, arguments);
        }
        else if(typeof(old) == 'function') {
            old.apply(object,arguments);
        }
    }
}
Just to clarify addMethod is not inbuilt method in JavaScript. We are writing our own method to achieve overloading.
If we see this method it take 3 arguments- object, name and fn.
object - the object on which we want to execute this method.
name - name of the function we want to overload.
fn - definition of function.

addMethod if you notice check the number of arguments and depending upon that it will identify if you have any method with the given name and same number of arguments, then it execute it.
To understand it more lets try to use it -
 function Person(){
    addMethod(this,'find',function(){
        alert('hi 0');
    });
    addMethod(this,'find',function(arg1){
        alert('hi 1')
    });
    addMethod(this,'find',function(arg1,arg2){
        alert('hi 2');
    })
}

var p = new Person();
p.find();
p.find('a');
p.find('a','b');

In above code once we create Person object, we are adding 3 new properties to Person, all has name find, but have different signature. In the addMethod, it appends these properties to person object. Once i call p.find(), it will try to find if Person has any function with name find and have 0 arguments in it. It will loop in that object until it finds it. If the function does not exist, it will exit.
If you attach a debugger and check the addMethod while execution you will find the first run we find argument.length as 0 and fn.length as 2(which is 3rd function), then it execute old.apply again and get the other find object, where it gets fn.length as 1 and finally as 0. Once it get the match it execute the find function.
Here we can not use call instead of apply, as the arguments are passed in the format of array.

Here is the whole code which executes different find methods in Person object-
function addMethod(object,name,fn){
    var old = object[name];
    object[name] = function() {
        if(fn.length == arguments.length) {
            fn.apply(object, arguments);
        }
        else if(typeof(old) == 'function') {
            old.apply(object,arguments);
        }
    }
}

function Person(){
    addMethod(this,'find',function(){
        alert('hi 0');
    });
    addMethod(this,'find',function(arg1){
        alert('hi 1')
    });
    addMethod(this,'find',function(arg1,arg2){
        alert('hi 2');
    })
}

var p = new Person();
p.find();
p.find('a');
p.find('a','b');

Saturday, September 8, 2012

Function/Variable Scope in JavaScript

Try to find the output of the following function -
function A(){
    this.myvar = 'a';
}
A();
alert(myvar);
var B = {
    myvar: 'B',
    C:function(){
        this.myvar = 'C';
    }
};
B.C();
alert(B.myvar);
alert(myvar);
Ans - a,C,a

once you declare this.myvar in function A, then actually we are creating a global variable. but when we are setting same value in function C within B, then actually its local value. In other words it is property of object, thus the value is set within object.
So actually function C is modifying the value of local variable named as myvar.
If we want to modify the global variable myvar within function C, then remove "this" before myvar, and directly set myvar = "C", it will modify the global variable.
To summarize- When it's an object property, the value is set within the object.

Now think about the output of this function -
function func(){
    return this;
}
alert(func()); ---- (1)

var myvar = {
    myfunc:func
}
alert(myvar.myfunc());-----(2)
In a function called directly without an explicit owner object, like case (1) causes the value of this to be the default object. case (1) is equivalent to calling window.myfunc().
In case 2 the calling object is myvar, thus the "this" object is actually myvar not window.
To Summarize - Function is a standard data type in JavaScript, an object indeed; you can pass them around and copy them. It's as if the entire function with argument list and body was copied and assigned.
In a function called using the method invocation syntax, like myvar.myfunc() or obj['myfunc'](), causes the value of this to be obj.
That's why although we declared function 'func' as global, instead of returning "window" as a value of "this" everytime, it returns it depending upon who calls it.

What if i don't want to declare the function inside this new variable, but still want to use it. Or else consider a case where a function need to be invoked on different objects. In above case , we will need to declare that function in each and every type of definition.
To overcome such situation we have "call" and "apply" method available.
We will simulate same example mentioned above to explore call and apply method.
function func(){
    return this;
}
alert(func());
var myvar = {
    name:'myname'
}
alert(func.call(myvar));
alert(func.apply(myvar));

The difference between these 2 methods comes when we pass some arguments. in case of call, we can directly pass the comma separated arguments, but in case of apply we need to pass these arguments in form of array. Here is the sample code -

function func(arg1,arg2){
    return [this,arg1,arg2];
}
var myvar = {
    name:'myname'
}
alert(func.call(myvar,'one','two'));
alert(func.apply(myvar,['one','two']));

To summarize- If we want to override the value of "this" without copying the function to another object, we can use "apply" or "call" and pass the required object in it.
NOTE- if we pass first parameter as null, then it is considered as global in javascript.

Lets try to understand Binding in JavaScript. Check the following code -
var Button = {
  click: function(){
    this.buttonclicked = true;
  }
};
var elem = document.createElement("li");
elem.onclick = Button.click;
elem.onclick();
alert(elem.buttonclicked); --> alerts true
alert(Button.buttonclicked); --> Alerts undefined

In the above example if you see, the 'buttonclicked' is the property of Button no element but still i see its available in element as well(of course accidentally).
In order to get the correct behavior we bind the Click property with Button. Check out the following code -
function bind(context, name){
  return function(){
    return context[name].apply(context, arguments);
  };
}
var Button = {
  click: function(){
    this.buttonclicked = true;
  }
};
var elem = document.createElement("li");
elem.innerHTML = "Click me!";
elem.onclick = bind(Button, "click");
elem.onclick();
alert(elem.buttonclicked); --> undefined
alert( Button.buttonclicked); --> true
in the above code we have bind the buttonclicked property with button.

To make it more generic its always possible to attach this bind property with function class itself.
If we define this on top of the page -
Function.prototype.bind = function(object){
  var fn = this;
  return function(){
    return fn.apply(object, arguments);
  };
};
then we can directly call - elem.onclick = Button.click.bind(Button);
because now every function has bind property associated with it.

Importance of new operator in JavaSCript-
Consider following example -
function A(){
    var name = "A";
}
var b = A();
var c = new A();
alert(typeof(b)); ----(1)
alert(typeof(c));-----(2)
In the above code b is undefined and type of c is object. In javascript new operator is used to create new object. Whenever we use "new" keyword, java script run time provides a new value of "this" object.

Thursday, September 6, 2012

JavaScript Tips and Tricks -5

1) Here are different ways in which you can define a JavaScript function -
a)
    function func(x){
    alert(x);}
    func('myName');
b)
    var func = function(x){
    alert(x);}
    func('myName');
c)
    var func = new Function("x" ,"alert(x);");
    func('myName');
d)
    window.func= function(x){ alert(x); };
    func('myName');

2) Sometimes in JavaScript the order of function definition does not matter. Here is the example -
if(typeof (func) == "undefined")
    alert('func is undefined');
else
    alert('func is not undefined');
function func(){ return true; }
The above alerts - func is not undefined.
But this statement is not true for any kind of assignment. Which includes the function assignment as well.
Which means if we defined function in any one of these format,it wont be possible to use them before assigning it. -
 window.func= function(x){ alert(x); };
 var func = new Function("x" ,"alert(x);");
 var func = function(x){alert(x);}
Which means following code will give output as "func is undefined" -
if(typeof (func) == "undefined")
    alert('func is undefined');
else
    alert('func is not undefined');   
var func = function(x){alert(x);}

3) We can always define functions below return statement. For example -
 function TestFunc(){
  alert(func());
  return func();
  function func(){ return true; }
}
TestFunc();
Above function will return as true.

4) Its always possible to have recursive calls in Java Script functions. Here is example-
function factorial(num){
    if(num == 0 || num == 1)
        return 1;
    else return num*factorial(num - 1);
}
alert(factorial(4));

5) How to implement Cache in JavaScript -
 var getSquare = function(num) {   
    if(getSquare.cache[num] == null)
        getSquare.cache[num] = num * num;
       
    return getSquare.cache[num];
}
getSquare.cache = {};

alert(getSquare(3));
alert(getSquare.cache[3]);

Saturday, September 1, 2012

SynhronizationContext

Que-Why do we need synchronization context?
Ans-The idea behind synchronization context is that a "source" thread can queue a delegate(piece of work) to the target thread. Generally in STA model(like UI components) we can't have multiple threads modifying the same component. Thus its required that only a single thread, dedicated to update UI, will do this job. In order to achieve this kind of design, Synchronization context was introduced. In other words is does the following-
1) provide synchronization(by allowing only one operation by s single thread at a time)
2) Queuing a unit of work from one thread to another.

Que-Is Synchronization context only for UI element?
Ans-The original purpose of synchronization context is to update the UI elements only. We can have its use to pass any unit of work to other non-ui threads as well. (Yet to get more info).

Que-What is the different between send and post?
Ans- Send/post are 2 ways by which we can marshal the code from one thread to another. The difference is send is a synchronous call  whereas post is an Async call. Send will wait till the operation is completed and then will come back. The calling thread will be blocked until it returns.

Que- When we marshal a code to UI thread and that code throws exception, then who is responsible to catch that exception?
Ans -
In case of send method - It is caught at calling thread not on the UI thread.
in case of post - it is on ui thread only.

Here is the example-
This code is executed in a form application.
 public void Run(Object state)
        {
            Debug.WriteLine("Run Thread Id - " + Thread.CurrentThread.ManagedThreadId);
            SynchronizationContext context = state as SynchronizationContext;
            try
            {
                context.Send(UpdateUI,null);  
            }
            catch (Exception ex) {
                Debug.WriteLine(ex.ToString());
            }
        }

        public void UpdateUI(object state) {
            throw new Exception();
        }

        private void button1_Click(object sender, EventArgs e)
        {
           
            Debug.WriteLine("Main Thread Id - " + Thread.CurrentThread.ManagedThreadId);
            SynchronizationContext uiContext = SynchronizationContext.Current;

            Thread t1 = new Thread(Run);
            t1.Start(uiContext);
        }

Que- What will be the ThreadId of DoWork? Same as Run thread or main thread?
static void Main(string[] args)
        {
            Console.WriteLine("Main thread is " + Thread.CurrentThread.ManagedThreadId);
            SynchronizationContext context = new SynchronizationContext();           
            SynchronizationContext.SetSynchronizationContext(context);
            Thread t1 = new Thread(Run);
            t1.Start(SynchronizationContext.Current);
            Console.ReadLine();
        }

        static void Run(object state)
        {
            Console.WriteLine("Run Thread ID: " + Thread.CurrentThread.ManagedThreadId);
            var context = state as SynchronizationContext;
            context.Send(DoWork, null);
            while (true)
                Thread.Sleep(10000000);
        }
        static void DoWork(object state)
        {
            Console.WriteLine("DoWork Thread ID:" + Thread.CurrentThread.ManagedThreadId);
        }
Ans- It will be same as Run Thread. As We can't use Synchronization context in this way. Actually the Synchronization Context provided by .NET does have it message pump. context pushes the messages to this message pump then UI thread picks these messages from this queue or message pump. In the above case the message pump us missing. If we want to achieve similar behavior, then we will have to implement our own queue, and will have to read items on UI thread using that queue.

Que- What is message pump?
Ans - A message loop is a small piece of code that exists in any native Windows program. It roughly looks like this:
while(GetMessage(&msg, NULL, 0, 0))
{
   TranslateMessage(&msg);
   DispatchMessage(&msg);
}
The GetMessage() Win32 API retrieves a message from Windows.TranslateMessage() is a helper function that translates keyboard messages. DispatchMessage() ensures that the window procedure is called with the message.
In the recent version of windows the order of messages is maintained.

Saturday, July 28, 2012

Inheritance in JavaScript

We all say we can have object oriented way of implementation in JavaScript. So lets see how can we inherit one class from another in JavaScript. In C# is very easy, writing a ":" will do it for you, but in JavaScript it is little tricky. We all know about prototype and constructor in java script(if you don't know please clear this concept from my previous post 'JavaScript tips and tricks -4'). In very simple words prototype gives you the instance of the base class and constructor gives you the instance of derived class.
Lets try to make inheritance between Pet and Dog class.
function Pet(name){
        this.getName = function(){return name;};
        this.setName = function(newName){name = newName;};
     }
function Dog(name, breed){
        this.getName = function(){return name;};
        this.getBreed = function() { return breed;};     
    }
Above code shows Dog constructor which takes name and breed as input and Pet constructor which takes name as input. Now we want to have toString method on Pet and Dog both. There are 2 ways to do it-
We can define it inside Class itself (perellel to this.getname method) or we can define it on prototype like this -
Pet.prototype.toString = function(){
        return "This pet Name is - " + this.getName();
    }
Dog.prototype.toString = function(){
        return "This is a Dog from prototype with NAme - " + this.getName() + " and Breed is - " + this.getBreed();
    }
If you remember from previous post how JavaScript execute any method on any object,you will understand the difference between 2 techniques.
Now lets put inheritance between these 2 classes -
    Dog.prototype = new Pet();
Now the prototype of Dog is a Pet, you can also call Dog as derived class of Pet.
Before we go into more detail of Dog and Pet, let me introduce one more property named as constructor.
consider another example -
function Person(){}
var p = new Person();
if(p.constructor === Person){
    alert('p.constructor === Person'); --> It will alert.
}
else{
    alert('p.constructor !== Person');
}
var p1 = new p.constructor();
if(p1 instanceof Person)
{
    alert('true'); --> TRUE
}
In the above example, if you see we created another object of Person using property constructor. Which means using constructor we can create object of same type, which can be proved once p1 instanceof Person alerts true. In order to achieve same objective we need to set the constructor property of Dog as well. But as we want this property to be there for all Dog objects, thus we will introduce it in the prototype function like this-
    Dog.prototype.constructor = Dog;
 If we dont set this property then we can't use this -
var dog1 = new dog.constructor();
It will not create another Dog object, instead it will create a Pet object, as constructor is available in Pet class.
If you remember inheritance in C#, whenever the object of derived class is initialized, its base class object need to initialized before that. The similar thing we will need to achieve in JavaScript as well to complete the inheritance. In order to do so, we can write call method of Pet in Dog constructor like this -
function Dog(name, breed){
        Pet.call(this, name);
        this.getBreed = function() { return breed;};      
    }
Now whenever a new Dog object is created it will automatically create Pet object as well. It completes our implementation of inheritance between Dog and Pet. Here is the full code -
    function Pet(name){
        this.getName = function(){return name;};
        this.setName = function(newName){name = newName;};
        //this.toString = function() {return "Pet with name " + this.getName();};
    }

    Pet.prototype.toString = function(){
        return "from prototype - This  pet Name is - " + this.getName();
    }

    var myPet = new Pet("pet1");
    alert(myPet);

    function Dog(name, breed){
        Pet.call(this, name);
        this.getBreed = function() { return breed;};
        //this.toString = function() {return "Dog with name " + this.getName();};
    }

    Dog.prototype = new Pet();
    Dog.prototype.constructor = Dog;

    Dog.prototype.toString = function(){
        return "This is a Dog from prototype with Name - " + this.getName() + " and Breed is - " + this.getBreed();
    }
    var dog = new Dog("Dog1", "Breed 1");
    alert(dog);

    alert(dog instanceof Dog);//true
    alert(dog instanceof Pet);//true
    alert(dog instanceof Object);//true
In order to check if inheritance was successful or not, you can always use "instanceof" method which gives true if the object is instance of given type.

Dog.prototype return object of Pet, which is base class for Dog.
constructor property returns you the constructor of that class. For example -
in above example dog.constructor does return constructor of Dog. It always possible to create another object (say dog1) of Dog using
var dog1 = new dog.constructor('dog2','breed2');

prototype can also used to modify existing object. For example we can add new method in inbuilt Array class -
if (!Array.prototype.forEach) {
  Array.prototype.forEach = function(fn){
    for ( var i = 0; i < this.length; i++ ) {
      fn( this[i], i, this );
    }
  };
}
var myArray = new Array('a', 'b', 'c');
myArray.forEach(function(value, index, array){
  alert(value + "-" + index + "-" + array)
});

Namespace in JavaScript-
JavaScript does support the namespaces. It helps us to avoid name collision. Here are some examples-
var namespace1 = {};
namespace1.var1 = function() {};
namespace1.var1.prototype.toString = function(){};

We can have multilevel namespaces also -
var namespace1 = {}
namespace1.namespace2 = {};
namespace1.namespace2.var1 = function(){};