Book Image

Object-Oriented JavaScript - Third Edition

By : Ved Antani, Stoyan STEFANOV
5 (1)
Book Image

Object-Oriented JavaScript - Third Edition

5 (1)
By: Ved Antani, Stoyan STEFANOV

Overview of this book

JavaScript is an object-oriented programming language that is used for website development. Web pages developed today currently follow a paradigm that has three clearly distinguishable parts: content (HTML), presentation (CSS), and behavior (JavaScript). JavaScript is one important pillar in this paradigm, and is responsible for the running of the web pages. This book will take your JavaScript skills to a new level of sophistication and get you prepared for your journey through professional web development. Updated for ES6, this book covers everything you will need to unleash the power of object-oriented programming in JavaScript while building professional web applications. The book begins with the basics of object-oriented programming in JavaScript and then gradually progresses to cover functions, objects, and prototypes, and how these concepts can be used to make your programs cleaner, more maintainable, faster, and compatible with other programs/libraries. By the end of the book, you will have learned how to incorporate object-oriented programming in your web development workflow to build professional JavaScript applications.
Table of Contents (25 chapters)
Object-Oriented JavaScript - Third Edition
Credits
About the Authors
About the Reviewer
www.PacktPub.com
Customer Feedback
Preface
Built-in Functions
Regular Expressions

Chapter 3, Functions


Lets do the following exercises:

Exercises

  1. To convert Hex colors to RGB, perform the following:

            function getRGB(hex) { 
              return "rgb(" + 
                parseInt(hex[1] + hex[2], 16) + ", " + 
                parseInt(hex[3] + hex[4], 16) + ", " + 
                parseInt(hex[5] + hex[6], 16) + ")"; 
            } 
            Testing: 
            > getRGB("#00ff00"); 
                   "rgb(0, 255, 0)" 
            > getRGB("#badfad"); 
                   "rgb(186, 223, 173)" 
    

    One problem with this solution is that array access to strings like hex[0] is not in ECMAScript 3, although many browsers have supported it for a long time and is now described in ES5.

    However, But at this point in the book, there was as yet no discussion of objects and methods. Otherwise an ES3-compatible solution would be to use one of the string methods, such as charAt(), substring(), or slice(). You can also use an array to avoid too much string concatenation:

        function getRGB2(hex) { 
          var result = []; 
          result.push(parseInt(hex.slice(1, 3), 16)); 
          result.push(parseInt(hex.slice(3, 5), 16)); 
          result.push(parseInt(hex.slice(5), 16)); 
          return "rgb(" + result.join(", ") + ")"; 
        } 
    

    Bonus exercise: Rewrite the preceding function using a loop so you don't have to type parseInt() three times, but just once.

  2. The result is as follows:

            > parseInt(1e1); 
            10 
            Here, you're parsing something that is already an integer: 
            > parseInt(10); 
            10 
            > 1e1; 
            10 
    

    Here, the parsing of a string gives up on the first non-integer value. parseInt() doesn't understand exponential literals, it expects integer notation:

            > parseInt('1e1'); 
            1 
    

    This is parsing the string '1e1' while expecting it to be in decimal notation, including exponential:

            > parseFloat('1e1'); 
            10 
    

    The following is the code line and its output:

            > isFinite(0 / 10); 
            true 
    

    Because 0/10 is 0 and 0 is finite.

    The following is the code line and its output:

            > isFinite(20 / 0); 
            false 
    

    Because division by 0 is Infinity:

            > 20 / 0; 
            Infinity 
    

    The following is the code line and its output:

            > isNaN(parseInt(NaN)); 
            true 
    

    Parsing the special NaN value is NaN.

  3. What is the result of:

            var a = 1; 
            function f() { 
              function n() { 
                alert(a); 
              } 
              var a = 2; 
              n(); 
            } 
            f(); 
    

    This snippet alerts 2 even though n() was defined before the assignment, a = 2. Inside the function n() you see the variable a that is in the same scope, and you access its most recent value at the time invocation of f() (and hence n()). Due to hoisting f() acts as if it was:

            function f() { 
              var a; 
              function n() { 
                alert(a); 
              } 
              a = 2; 
              n(); 
            } 
    

    More interestingly, consider this code:

            var a = 1; 
            function f() { 
              function n() { 
                alert(a); 
              } 
              n(); 
              var a = 2; 
              n(); 
            } 
            f(); 
    

    It alerts undefined and then 2. You might expect the first alert to say 1, but again due to variable hoisting, the declaration (not initialization) of a is moved to the top of the function. As if f() was:

            var a = 1; 
            function f() { 
              var a; // a is now undefined 
              function n() { 
                alert(a); 
              } 
              n(); // alert undefined 
              a = 2; 
              n(); // alert 2 
            } 
            f(); 
    

    The local a "shadows" the global a, even if it's at the bottom.

  4. Why all these alert "Boo!"

    The following is the result of Example 1:

            var f = alert; 
            eval('f("Boo!")'); 
    

    The following is the result of Example 2. You can assign a function to a different variable. So f() points to alert(). Evaluating this string is like doing:

            > f("Boo"); 
    

    The following is the output after we execute eval():

            var e; 
            var f = alert; 
            eval('e=f')('Boo!'); 
    

    The following is the output of Example 3. eval() returns the result on the evaluation. In this case it's an assignment e = f that also returns the new value of e. Like the following:

            > var a = 1; 
            > var b; 
            > var c = (b = a); 
            > c; 
            1 
    

    So eval('e=f') gives you a pointer to alert() that is executed immediately with "Boo!".

    The immediate (self-invoking) anonymous function returns a pointer to the function alert(), which is also immediately invoked with a parameter "Boo!":

            (function(){ 
              return alert; 
            })()('Boo!');