Monday, May 11, 2015

Important Things in JavaScript | Closure in JavaScript | New Operators in JavaScript

1) Extension Method or Prototype in JavaScript



<script type="text/javascript">
            function Person(fname, lname) {
                this.firstName = fname;
                this.lastName = lname;
            }


            Person.prototype = {
                model: {
                    name: "Welcome"
                },
                eventbinder: function () {
                    return this.controller(); //.eventbinder();
                },
                controller: function () {
                    alert(this.model.name);
                },
                obj: "hello"
            };
            var p = new Person("Hari", "Prasad");
            var s = p.controller();
            var d = p.obj;
        </script>


2) Closure in JavaScript

A closure is a function having access to the parent scope, even after the parent function has closed.

Normally, the local variables within a function only exist for the duration of that function's execution.

var add = (function () {
    var counter = 0;
    return function () {return counter += 1;}
})();

add();
add();
add();


3)  Differentiate between == and ===?

Both are companrision operator in javascript and use to compare values. Difference between **

== and === is

While using == javascript use typeCast before comparing variables. For example:-

var j=1,c="1";
console.log(j==c)      // Will result True

console.log(j===c)      // Will result False

Because === operator doesn't perform typeCasting it is faster than == operator.

!== Also follow the same behaviour deffrence compare to != Operator.