JavaScript Object Oriented Using Object

From CoderLearner
Jump to: navigation, search

Description

JavaScript Object Notation, and how to create object properties and method. Object's methods and properties are defined by a comma delimited. Each start with the object's name followed by a colon and then the definition.

Syntax


var doggy = {
   color:'black',
   weight:20,
   speak: function( say ) {
      console.log(say);
   }
}

Example 1

<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script type="text/javascript"  src="jquery-1.8.3.js"></script>
        <script>
            $().ready(function() {
                var ck = {
                    color: 'green',
                    series: 50,
                    op: function() {
                        console.log('Tis is function')
                    }
                }


                console.log(ck.color);
                console.log(ck.series);
                console.log(ck.op());

            });

        </script>
    </head>

    <body>
        <div>TODO write content</div>
        <p></p>
    </body>
</html>

Example 2

Using the JSON object to assign to the list for display.

<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script type="text/javascript"  src="jquery-1.8.3.js"></script>
        <script>
            $().ready(function() {
                var ck = {
                    color: 'green',
                    series: 50,
                    msg: '',
                    op: function(msg) {
                        ck.msg = msg;
                        return ck.msg;
                    }
                }

                /*
                 * //alert message
                 alert(ck.color);
                 alert(ck.op('Great Message'));
                 alert(ck.msg);
                 */
// assign to html 
                $('#color').html(ck.color);
                $('#op').html(ck.op('Great World'));
                $('#series').html(ck.series);
                $('#msg').html(ck.msg);
// reassign the msg value
                ck.msg = 'Wonder World';
                $('#msg').html(ck.msg);

            });

        </script>
    </head>

    <body>
        <ul>
            <li><span id="color"></span></li>
            <li><span id="op"></span></li>
            <li><span id="series"></span></li>
            <li><span id="msg"></span></li>

        </ul>
    </body>
</html>