Monday, 9 January 2017

Easiest way to create javascript callback function

What we are going to cover here are:

  •  Creation of JavaScript Custom Object.
  •  Create property and mehtod for JavaScript.
  •  Create callback function.
  •  Create parameterized callback function.
  •  Call callback function.


 As said One picture explain 1000 words, i say once example will demonstrate above topic. :)


<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script type="text/javascript">
        var myObj =  {
            name: 'raj',
            age: 27, // 27/16
            IsMature: function (myCallback) {
                console.log('1: Before callback');
                if (myCallback && typeof (myCallback) === "function") {
                    //myCallback();
                    if (this.age > 18) {
                        myCallback(true); // call with parameter
                    }
                    else {
                        myCallback(false);
                    }

                }
            }
        };

        myObj.IsMature(function (status) {
            console.log('2: After callback');
            console.log('Status:' + status);
        });
    </script>

</head>
<body>

</body>
</html>

Output:
1: Before callback
2: After callback
Status:true