Thursday, May 26, 2016

JS Series: Function vs. Object Encapsulation

While going through JS and trying to figure out how functions work vs. objects since you know, functions are objects, I decided to put together a short example of how encapsulation works in JavaScript. Basically you can create private and public fields and methods but not inside an object you have to use a function.

I'm well aware there are many more cases where this basic principle gets confusing or misused. An example where this all falls apart is changing out the var keyword on the cnt property inside the CalculatorFunction.js file. However this is meant to be a very simple example of how you can hide fields inside a file. You can do the same thing for methods by not doing a this.func = function() and instead just declaring the function() you wish to use privately.

Explanation
The concept behind this test was to create the same thing as an object and a function. Call the method to add two values together. In this add function it should increase the cnt of methods executed and store that value. After calling that method the program tries to modify the cnt field in both types to see the result. In the function the cnt is protected and in the object it is not.


Screenshot of my results



Index.html

<html>

<body>
    <h1>Scoping Tests</h1>
    <script src="CalculatorObject.js"></script>
    <script src="CalculatorFunction.js"></script>

    <script>
        var a = 5;
        var b = 25;
        var c = 30;

        var cf = new CalculatorFunction();

        var rslt1 = calculatorObject.add(a, b);
        rslt1 = rslt1 + calculatorObject.add(b, c);
        var rslt2 = cf.add(a, c);

        document.write("Result1->" + rslt1 + " count->" + calculatorObject.getCnt());
        document.write("<br/>Result2->" + rslt2 + " count->" + cf.getCnt());
        
        
        /* Testing function encapsulation using var */
        document.write("<br/><br/><b>Test Function Encapsulation</b><br/>");
        cf.cnt = 25;
        document.write("<br/>Setting cf.cnt = 25 won't matter. getCnt() is still: " + cf.getCnt() + " aka encapsulation in JS.");
        
        
        /* Testing object encapsulation using object parameters */
        document.write("<br/><br/><b>Test Object Encapsulation</b><br/>");
        calculatorObject.cnt = 999;
        document.write("<br/>Setting calculatorObject.cnt = 999. getCnt() on object should return 999: " + calculatorObject.getCnt() + " aka non-encapsulation.");
        
    </script>
</body>

</html>


CalculatorObject.js

var calculatorObject = {
    "cnt": 0,
   
    "add": function (a, b) {
        'use strict';
        this.cnt = this.cnt + 1;
        return a + b;
    },
   
    "subtract": function (a, b) {
        'use strict';
        this.cnt = this.cnt + 1;
        return a - b;
    },
   
    "getCnt": function () {
        'use strict';
        return this.cnt;
    }
};


CalculatorFunction.js

function CalculatorFunction() {
   
    'use strict';
    var cnt = 0;
    console.log(cnt);
    this.add = function (a, b) {
        cnt = cnt + 1;
        return a + b;
    };

    this.subtract = function (a, b) {
        cnt = cnt + 1;
        return a - b;
    };

    this.getCnt = function () {
        return cnt;
    };

}


Though this is a very small and simple example it will help you to understand just how these two items work in relation to what problem you are trying to solve in your source code.

Enjoy!

JS Series: JavaScript xmlHttp GET Request


In this post I will provide a code sample for how to do simple xmlHttp GET requests and update a unordered list of times to display great nerdy Chuck Norris quotes using the icndb (Internet Chuck Norris Database).

In order to keep things simple at the beginning I'm going to try write all my JavaScript in the same html file. Once we move to modules and server side I'm sure that won't be possible but for now let's keep things simple. 


1. Create a new file called index.html and paste the following code into the file and save.

<script>
    function httpGetAsync() {  
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function() { 
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
            callback(xmlHttp.responseText);
        }
    }
    xmlHttp.open("GET", "http://api.icndb.com/jokes/random", true); // true for asynchronous 
    xmlHttp.send(null);
}

function callback(respString) {
            var joke = getJoke(respString);
            var quoteList = document.getElementById("quoteList");
            var li = document.createElement("li");
            li.appendChild(document.createTextNode(joke));
            quoteList.appendChild(li);
}

function getJoke(respString) {
    var obj = JSON.parse(respString);
    return obj.value.joke;
}

</script>
<input type="button" value="Get Quote" onclick="httpGetAsync()" />
<ul id="quoteList"></ul>

2. Open The File With Your Browser

Locate the new index.html file you just created and double click on it. This should open the file along with the script code into your browser. You should be supplied with a single button with a label called "Get Quote". Clicking on this button will fire off an asynchronous get request to the incdb server and return a string of data (JSON format) which we will show in the browser.




ScreenShot



Items To Note

  • There was a button added to the page which called the httpGetAsync() JS function.
  • The httpGetAsync method created a new xmlHttp object and opened a GET connection to a specific URL and called send.
  • The xmlHttp object created has a callback function assigned when the state of the connection changed.
  • This change fired off a call to a new method aptly named callback which took the response json returned. 
  • The response json (JavaScript Object Notation) was then created using the JSON.parse method which takes a regular string and creates the actual JSON object.
  • This method also accesses the joke object value and returns it to the calling function.
  • Next the callback finds the UL tag by id, creates a new LI element, appends the joke text into that LI tag, then appends that LI back into the UL tag so the list continues to grow each time you hit the Get Quote button.

I hope you enjoyed this simple yet powerful example of how to do a GET with JavaScript. As I continue down this path I look forward to the many challenges I will face. I can already tell just how powerful this whole JS thing is nowadays with this simple script. 

Enjoy!


JavaScript oh JavaScript

The World is eati.. wait.. no JavaScript is eating the world. That is the headline I keep reading everywhere I look. I have been coding JavaScript since the nineties. I have never really given JS any respect mainly because it was always just a toy language or something to add a little functionality to a web page. Well times sure have changed and it seems like everywhere I look you can use JS to do about anything from IOT to server side programmer and beyond.

For this reason I have decided to embark on a new journey to the land of current JS. I'll try to post new articles as I teach myself all the new features in say ES6 to how to do try module encapsulation (looking forward to that one) and also our best friend Node.js which along with npm is one heck of a tool. So buckle in as we take a very seasoned veteran Java programmer and build out tools and products using nothing but JavaScript.