Getting to understand JavaScripts prototypal nature

One of the things that are quite weird to get use to, from a C# developer’s perspective, is JavaScript’s prototypical nature. Check out this basic example:


var objXMLHTTP =
{
    getXMLHTTPObject: function(url,elementName) {
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        }
        else if (window.ActiveXObject) {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        else {
            alert("Your browser does not support XMLHTTP!");
        }
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4) {
                document.getElementById(elementName).innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open("GET", url, true);
        xmlhttp.send(null);
    }
};
objXMLHTTP.getXMLHTTPObject("http://localhost/YieldTester/Handler.ashx", "testDiv");

The code above creates a simple XMLHTTPRequest object, but you do not create an instance of the object, you call it directly. Note objXMLHTTP.getXMLHTTPObject. In C# you might have created an object and then you instantiate it through an instance of that object. I have taken the code as is given on W3Schools and modified it a little.

  • Share/Bookmark

Leave a Reply

Get Adobe Flash playerPlugin by wpburn.com wordpress themes