KEMBAR78
OO in JavaScript | PPTX
OO in JavaScriptGunjan Kumar
AgendaJavaScript you need to knowOO in JavaScript OO basicsInheritanceEncapsulationPolymorphismClassObject and propertiesObject literals (JSON)Functions and function context,Anonymous functionsPrototype and inheritanceClosureunobtrusive JavaScript - the way our code should be structured
OO in JSPrototype-based programming is a style of object-oriented programming in whichclasses are not presentbehavior reuse (inheritance) is accomplished through a process of decorating existing objects which serve as prototypes. This model is also known as class-less, prototype-oriented, or instance-based programming.Support in JS : Inheritance - The ability to define the behavior of one object in terms of another by sub-classing. Encapsulation - Support for method calls on a JavaScript object as a member of a ClassPolymorphism - The ability for two classes to respond to the same (collection of) methods.
InheritanceInheritanceallows one class to replicate and extend the functionality of another without having to re-implement the existing class’s behaviorJavaScript only supports single class inheritanceSupported by prototype and other options in JSMore details later in the slides
EncapsulationEncapsulationensures that an object’s state can only be changed by the object itself, as a result of that object’s performing one of the operations (methods) it supports. Supported by defining variables in function with this. And then defining  functions to access these variables      function A(){    var x = 7;this.GetX = function () { return x; }this.SetX = function (xT) { x = xT; }        }obj = new A;        obj2 = new A;document.write(obj.GetX() + ' ' + obj2.GetX());obj.SetX(14);document.write(' ' + obj.GetX() + ' ' + obj2.GetX());        //alert(obj.x);//gives undefined
AbstractionAbstractionkey concept that underpins the very notion of objects - that they abstract the details of their own implementation.This can be achieved by inheritance (specialization), or composition. JavaScript achieves specialization by inheritance, and composition by letting instances of classes be the values of attributes of other objects
PolymorphismPolymorphismability to appear in different forms. allows an object of a given class to be treated as if it were an object of its superclass, despite the fact that one or more of the superclass’s methods may be defined differently (overridden) in the object’s true class.In JS, different classes can define methods with the same name; methods are scoped to the class in which they're defined.Achieved by simply having different object classes implement a collection of methods that use the same names. Then, a caller, need just use the correctly named function property to invoke the appropriate function for each object type.
Polymorphismfunction A()    {    this.x = 1;    } A.prototype.DoIt = function()   // Define Method    {    this.x += 1;    }     function B()    {    this.x = 1;    } B.prototype.DoIt = function()    // Define Method    {    this.x += 2;    }    a = new A;    b = new B;a.DoIt();b.DoIt();document.write(a.x + ', ' + b.x);
The ClassJavaScript is a prototype-based language which contains no class statement, such as is found in C++ or Java. This is of relevance ONLY if we expect multiple objects with same properties – thus reducing the lines of codeNo formal way to define a class. Any function definition is a classProperties and methods can be defined within the functionTo instantiate, we use the new keywordWe can define the function to accept parameters to simulate a constructor which sets default params
The Classfunction Owner(_name, _age) {            this.name = _name;this.age = _age;        }function Bike(_name, _model, _make, _mileage, _owner) {            this.name = _name;this.model = _model;this.make = _make;this.mileage = _mileage;this.owner = _owner;this.whatAmI = function () { return this.year + ' ' + this.make + ' ' + this.model; }        }var bike3 = new Bike('Yamaha3', 'Model 3', new Date(2008, 3, 12), 33, new Owner('owner 3', 33));
The ObjectCreate object by new Object()No properties by default. Keep adding dynamically.primary purpose of an Object instance to serve as a container for a named collection of other objectsThe name of a property is a stringValue can be any JavaScript object, be it a Number, String, Date, Array, basic Object, or any other JavaScript object type (including functions)
The ObjectYou can also create instance of the Classfunction Bird() { 	alert(“bird created”);} var crow= new Bird(); varcannary= new Bird(); The constructor is called each time the instance is created
The ObjectCreating and populating an objectvar ride = new Object();ride.make = 'Yamaha';ride.model = 'V-Star Silverado 1100';ride.year = 2005;ride.purchased = new Date(2005, 3, 12);var owner = new Object();        owner.name = 'Spike Spiegel';owner.occupation = 'bounty hunter';ride.owner = owner;
The Objectobject hierarchy shows that Objects are containers for named references to other Objects or JavaScript built-in objects
The ObjectAccessing values from object$(document).ready(function () {            $(".container").append("<tr><td>Make</td><td>" + ride.make + "</td></tr>");            $(".container").append("<tr><td>Model</td><td>" + ride.model + "</td></tr>");            $(".container").append("<tr><td>Year</td><td>" + ride.year + "</td></tr>");            $(".container").append("<tr><td>Purchased</td><td>" + ride.purchased + "</td></tr>");            $(".container").append("<tr><td>Owner Name</td><td>" + ride.owner.name + "</td></tr>");            $(".container").append("<tr><td>Owner Occupation</td><td>" + ride.owner.occupation + "</td></tr>");        });Another way of accessing propertiesride["Clumsy Property"] = 'Really clumsy value';$(".container").append("<tr><td>Clumsy Value</td><td>" + ride["Clumsy Property"] + "</td></tr>");This is useful for names that have spaces / (.) dots
Object Literals (JSON)var ride = new Object();ride.make = 'Yamaha';ride.model = 'V-Star Silverado 1100';ride.year = 2005;ride.purchased = new Date(2005, 3, 12);        ride["Clumsy Property"] = 'Really clumsy value';var owner = new Object();        owner.name = 'Spike Spiegel';owner.occupation = 'bounty hunter';ride.owner = owner;varrideJSON = {            make: 'Yamaha',            model: 'V-Star Silverado 1100',            year: 2005,            purchased: new Date(2005, 3, 12),            'Clumsy Property' : 'Really clumsy value',            owner: {                name: 'Spike Spiegel',                occupation: 'bounty hunter'            }        };JavaScript Object Notation allows us to define object using literals	- we no longer need to instantiate new Object()	- reduces the work of defining name and then assigning value
JSON : Rules for definition{     "firstName": "John",     "lastName": "Smith",     "age": 25,     "address":     {         "streetAddress": "21 2nd Street",         "city": "New York",         "state": "NY",         "postalCode": "10021"     },     "phoneNumber":     [         {           "type": "home",           "number": "212 555-1234"         },         {           "type": "fax",           "number": "646 555-4567"         }     ] }{ defines start of a an object. } defines the end.[ defines start of an array. ] defines the end.Name and values are separated by :
Summary so farA JavaScript object is an unordered collection of properties.Properties consist of a name and a value.Objects can be declared using new Object()object literalsinstantiating a “class”Top-level variables are properties of window.all of the following statements are equivalent:varfoo = bar; and window.foo = bar; and foo = bar;
FunctionsSimilar to any other typeFunction instances are values that can be assigned to variables, properties, or parameters just like instances of other object typesFollowing are the same :function hello(){ alert('Hi there!'); } hello = function(){ alert('Hi there!'); }window.hello = function(){ alert('Hi there!'); }
Functions : adding as propertyvar ride = {make: 'Yamaha',model: 'V-Star Silverado 1100',year: 2005,purchased: new Date(2005,3,12),owner: {name: 'Spike Spiegel',occupation: 'bounty hunter'},whatAmI: function() {return this.year+' '+this.make+' '+this.model;}};
Functions contd.
Functions contd.Functions can be passed as parameter setTimeout(function() { alert('Hi there!'); },5000);Context in functionobject referenced by this—termed the function contextIn the default case, the context (this) of an invocation of the function is the object whose property contains the reference used to invoke the functionIf you are using call(), you can specify the context and params
Function ContextFunction context describes the object that’s referenced by the thispointer during the invocation of a function.var o1 = {handle:'o1'};var o2 = {handle:'o2'};var o3 = {handle:'o3'};window.handle = 'window';      function whoAmI(messageText) {        return this.handle + " , message text : " + messageText;      }      o1.identifyMe = whoAmI;      alert(whoAmI("message text window"));      alert(o1.identifyMe("message text o1"));      alert(whoAmI.call(o2, "message text o2"));      alert(whoAmI.apply(o3, "message text o3"));A function f acts as a method of object o when o serves as the function context of theinvocation of f.
Anonymous FunctionsDeclaring functions inline rather than separately IF IT IS USED ONLY ONCE.var employee2 = {empID: 57,firstName: 'Gunjan',lastName: 'Kumar',whoAmI: function () {                return "Emp ID : " + this.empID + " First Name : " + this.firstName + " Last Name : " + this.lastName;            }        };These are faster since name resolution is costlyShould be typically used when system does a call – like windows.onload	When you are going to call, typically named functions are used
PrototypeAllows you to add new properties / methods to classHelps in implementing inheritance of sorts – you can instantiate objects of older type and then add additional properties to the “class”AdvantagesYou can add methods to “classes” you didn’t createthe functions are only stored once (in the prototype object), rather than in every new objectWhen evaluating an expression to retrieve a property, JavaScript first looks to see if the property is defined directly in the object. If it is not, it then looks at the object's prototype to see if the property is defined there. This continues up the prototype chain until reaching the root prototype
Prototype exampleString.prototype.convertUnderscores = function () {            return this.replace(/_/g, " ");        };var underscored = "Are_there_any_spaces_in_here?";var spaced = underscored.convertUnderscores();        alert(spaced);        function Bird() {this.feet = 2;this.feathers = true;            return true;        }var bird1 = new Bird();        alert(bird1.getFeetNum);Bird.prototype.getFeetNum = function () {            return this.feet;        };var bird2 = new Bird();        alert(bird2.getFeetNum());
Inheritance using prototypefunction Bird() {this.feet = 2;this.feathers = true;            return true;        } function Canary() {this.color = "yellow";            return true;        }Canary.prototype = new Bird(); //defining parent class if you willvartweety = new Canary();        alert("Feet : " + tweety.feet + 	" Color : " + tweety.color +	" Feathers : " + tweety.feathers);function Crow() {this.superclass = Bird;this.superclass();this.color = "black";            return true;        }
Inheritance using prototype// define the Person Class  function Person() { }Person.prototype.sayHello = function () {            alert('hello');        };// define the Student classfunction Student() { }// inherit PersonStudent.prototype = new Person();// correct the constructor pointer because it points to PersonStudent.prototype.constructor = Student;// replace the sayHello methodStudent.prototype.sayHello = function () {            alert('hi, I am a student');        }// add sayGoodBye methodStudent.prototype.sayGoodBye = function () {            alert('goodBye');        }var student1 = new Student();student1.sayHello();student1.sayGoodBye();
NamespaceNo inherent way to prevent name conflict – if 2 people define same named “class”, the later definition will be used.Namespace is implemented by typically using domain names with the class name BUT that implies each part of the Domain Name has to be defined
Namespace exampleif (typeof com == "undefined") {            com = new Object();        }        if (typeofcom.qwest == "undefined") {com.qwest = new Object();        }com.qwest.Bird = function() {this.feet = 2;this.feathers = true;this.color = "yellow";            return true;        }        Bird = function () {this.feet = 2;this.feathers = true;this.color = "black";            return true;        }
ClosureClosure is a Function instance coupled with the local variables from its environment that are necessary for its execution.How this manifests : For a function, a variable defined in its scope at the point of declaration, is carried along with the function even after the point of declaration has gone out of scope, closing the declaration$(function () {var local = 1;window.setInterval(function () {                $('#display')            .append('<div>At ' + new Date() + ' local=' + local + '</div>');                local++;            }, 3000);        });
Closure contd.Another important feature of closures is that a function context is never included as part of the closure.this.id = 'someID';$('*').each(function(){alert(this.id);});Here this.id will give the id property for the function context of each which is NOT same as the one with someIDthis.id = 'someID';var outer = this;$('*').each(function(){alert(outer.id);});Here , the variable outer is defined in the scope of the function and hence by closure, it can access the same
Unobtrusive JavaScriptWhat is it?Not a formal term but refers to an approach on how to use JavaScript in web pagesPrimarily talks about separation of behavior from presentation (sounds familiar??)<input type="text" name="date" onchange="validateDate()" />Vs.<input type="text" name="date" id="date" />$(function(){    $('#date').bind('change', validateDate);});
Unobtrusive JavaScript (contd.)purpose of markup is to describe a structurecombining the structure and behavior negatively impacts maintainability inline event handlers are harder to use and maintain specially when one needs to set handlers for several events on a single element	when one wants to set the same event handler on several elements	when one is using event delegationIn essence, this is asking for a separate .JS file that contains all the behavior and attaches the same to markup.Typically this would result in three set of filesHtml (markup)CSS (presentation)JS (behavior)
Unobtrusive JavaScript  ReferenceReference :http://en.wikipedia.org/wiki/Unobtrusive_JavaScripthttp://icant.co.uk/articles/seven-rules-of-unobtrusive-javascript/http://www.onlinetools.org/articles/unobtrusivejavascript/chapter1.htmlhttp://labs.adobe.com/technologies/spry/articles/best_practices/separating_behavior.html
JSON Referenceshttp://en.wikipedia.org/wiki/JSONhttp://www.json.org/http://www.hunlock.com/blogs/Mastering_JSON_(_JavaScript_Object_Notation_)http://www.jsonlint.com/ : this allows you to validate / format json stringhttps://github.com/douglascrockford/JSON-jsvarmyJSONText = JSON.stringify(myObject) varmyObject = JSON.parse(myJSONtext)http://api.jquery.com/jQuery.parseJSON/http://api.jquery.com/jQuery.getJSON/varobj = jQuery.parseJSON('{"name":"John"}');	alert( obj.name === "John" );

OO in JavaScript

  • 1.
  • 2.
    AgendaJavaScript you needto knowOO in JavaScript OO basicsInheritanceEncapsulationPolymorphismClassObject and propertiesObject literals (JSON)Functions and function context,Anonymous functionsPrototype and inheritanceClosureunobtrusive JavaScript - the way our code should be structured
  • 3.
    OO in JSPrototype-basedprogramming is a style of object-oriented programming in whichclasses are not presentbehavior reuse (inheritance) is accomplished through a process of decorating existing objects which serve as prototypes. This model is also known as class-less, prototype-oriented, or instance-based programming.Support in JS : Inheritance - The ability to define the behavior of one object in terms of another by sub-classing. Encapsulation - Support for method calls on a JavaScript object as a member of a ClassPolymorphism - The ability for two classes to respond to the same (collection of) methods.
  • 4.
    InheritanceInheritanceallows one classto replicate and extend the functionality of another without having to re-implement the existing class’s behaviorJavaScript only supports single class inheritanceSupported by prototype and other options in JSMore details later in the slides
  • 5.
    EncapsulationEncapsulationensures that anobject’s state can only be changed by the object itself, as a result of that object’s performing one of the operations (methods) it supports. Supported by defining variables in function with this. And then defining functions to access these variables function A(){ var x = 7;this.GetX = function () { return x; }this.SetX = function (xT) { x = xT; } }obj = new A; obj2 = new A;document.write(obj.GetX() + ' ' + obj2.GetX());obj.SetX(14);document.write(' ' + obj.GetX() + ' ' + obj2.GetX()); //alert(obj.x);//gives undefined
  • 6.
    AbstractionAbstractionkey concept thatunderpins the very notion of objects - that they abstract the details of their own implementation.This can be achieved by inheritance (specialization), or composition. JavaScript achieves specialization by inheritance, and composition by letting instances of classes be the values of attributes of other objects
  • 7.
    PolymorphismPolymorphismability to appearin different forms. allows an object of a given class to be treated as if it were an object of its superclass, despite the fact that one or more of the superclass’s methods may be defined differently (overridden) in the object’s true class.In JS, different classes can define methods with the same name; methods are scoped to the class in which they're defined.Achieved by simply having different object classes implement a collection of methods that use the same names. Then, a caller, need just use the correctly named function property to invoke the appropriate function for each object type.
  • 8.
    Polymorphismfunction A() { this.x = 1; } A.prototype.DoIt = function() // Define Method { this.x += 1; } function B() { this.x = 1; } B.prototype.DoIt = function() // Define Method { this.x += 2; } a = new A; b = new B;a.DoIt();b.DoIt();document.write(a.x + ', ' + b.x);
  • 9.
    The ClassJavaScript isa prototype-based language which contains no class statement, such as is found in C++ or Java. This is of relevance ONLY if we expect multiple objects with same properties – thus reducing the lines of codeNo formal way to define a class. Any function definition is a classProperties and methods can be defined within the functionTo instantiate, we use the new keywordWe can define the function to accept parameters to simulate a constructor which sets default params
  • 10.
    The Classfunction Owner(_name,_age) { this.name = _name;this.age = _age; }function Bike(_name, _model, _make, _mileage, _owner) { this.name = _name;this.model = _model;this.make = _make;this.mileage = _mileage;this.owner = _owner;this.whatAmI = function () { return this.year + ' ' + this.make + ' ' + this.model; } }var bike3 = new Bike('Yamaha3', 'Model 3', new Date(2008, 3, 12), 33, new Owner('owner 3', 33));
  • 11.
    The ObjectCreate objectby new Object()No properties by default. Keep adding dynamically.primary purpose of an Object instance to serve as a container for a named collection of other objectsThe name of a property is a stringValue can be any JavaScript object, be it a Number, String, Date, Array, basic Object, or any other JavaScript object type (including functions)
  • 12.
    The ObjectYou canalso create instance of the Classfunction Bird() { alert(“bird created”);} var crow= new Bird(); varcannary= new Bird(); The constructor is called each time the instance is created
  • 13.
    The ObjectCreating andpopulating an objectvar ride = new Object();ride.make = 'Yamaha';ride.model = 'V-Star Silverado 1100';ride.year = 2005;ride.purchased = new Date(2005, 3, 12);var owner = new Object(); owner.name = 'Spike Spiegel';owner.occupation = 'bounty hunter';ride.owner = owner;
  • 14.
    The Objectobject hierarchyshows that Objects are containers for named references to other Objects or JavaScript built-in objects
  • 15.
    The ObjectAccessing valuesfrom object$(document).ready(function () { $(".container").append("<tr><td>Make</td><td>" + ride.make + "</td></tr>"); $(".container").append("<tr><td>Model</td><td>" + ride.model + "</td></tr>"); $(".container").append("<tr><td>Year</td><td>" + ride.year + "</td></tr>"); $(".container").append("<tr><td>Purchased</td><td>" + ride.purchased + "</td></tr>"); $(".container").append("<tr><td>Owner Name</td><td>" + ride.owner.name + "</td></tr>"); $(".container").append("<tr><td>Owner Occupation</td><td>" + ride.owner.occupation + "</td></tr>"); });Another way of accessing propertiesride["Clumsy Property"] = 'Really clumsy value';$(".container").append("<tr><td>Clumsy Value</td><td>" + ride["Clumsy Property"] + "</td></tr>");This is useful for names that have spaces / (.) dots
  • 16.
    Object Literals (JSON)varride = new Object();ride.make = 'Yamaha';ride.model = 'V-Star Silverado 1100';ride.year = 2005;ride.purchased = new Date(2005, 3, 12); ride["Clumsy Property"] = 'Really clumsy value';var owner = new Object(); owner.name = 'Spike Spiegel';owner.occupation = 'bounty hunter';ride.owner = owner;varrideJSON = { make: 'Yamaha', model: 'V-Star Silverado 1100', year: 2005, purchased: new Date(2005, 3, 12), 'Clumsy Property' : 'Really clumsy value', owner: { name: 'Spike Spiegel', occupation: 'bounty hunter' } };JavaScript Object Notation allows us to define object using literals - we no longer need to instantiate new Object() - reduces the work of defining name and then assigning value
  • 17.
    JSON : Rulesfor definition{ "firstName": "John", "lastName": "Smith", "age": 25, "address": { "streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": "10021" }, "phoneNumber": [ { "type": "home", "number": "212 555-1234" }, { "type": "fax", "number": "646 555-4567" } ] }{ defines start of a an object. } defines the end.[ defines start of an array. ] defines the end.Name and values are separated by :
  • 18.
    Summary so farAJavaScript object is an unordered collection of properties.Properties consist of a name and a value.Objects can be declared using new Object()object literalsinstantiating a “class”Top-level variables are properties of window.all of the following statements are equivalent:varfoo = bar; and window.foo = bar; and foo = bar;
  • 19.
    FunctionsSimilar to anyother typeFunction instances are values that can be assigned to variables, properties, or parameters just like instances of other object typesFollowing are the same :function hello(){ alert('Hi there!'); } hello = function(){ alert('Hi there!'); }window.hello = function(){ alert('Hi there!'); }
  • 20.
    Functions : addingas propertyvar ride = {make: 'Yamaha',model: 'V-Star Silverado 1100',year: 2005,purchased: new Date(2005,3,12),owner: {name: 'Spike Spiegel',occupation: 'bounty hunter'},whatAmI: function() {return this.year+' '+this.make+' '+this.model;}};
  • 21.
  • 22.
    Functions contd.Functions canbe passed as parameter setTimeout(function() { alert('Hi there!'); },5000);Context in functionobject referenced by this—termed the function contextIn the default case, the context (this) of an invocation of the function is the object whose property contains the reference used to invoke the functionIf you are using call(), you can specify the context and params
  • 23.
    Function ContextFunction contextdescribes the object that’s referenced by the thispointer during the invocation of a function.var o1 = {handle:'o1'};var o2 = {handle:'o2'};var o3 = {handle:'o3'};window.handle = 'window'; function whoAmI(messageText) { return this.handle + " , message text : " + messageText; } o1.identifyMe = whoAmI; alert(whoAmI("message text window")); alert(o1.identifyMe("message text o1")); alert(whoAmI.call(o2, "message text o2")); alert(whoAmI.apply(o3, "message text o3"));A function f acts as a method of object o when o serves as the function context of theinvocation of f.
  • 24.
    Anonymous FunctionsDeclaring functionsinline rather than separately IF IT IS USED ONLY ONCE.var employee2 = {empID: 57,firstName: 'Gunjan',lastName: 'Kumar',whoAmI: function () { return "Emp ID : " + this.empID + " First Name : " + this.firstName + " Last Name : " + this.lastName; } };These are faster since name resolution is costlyShould be typically used when system does a call – like windows.onload When you are going to call, typically named functions are used
  • 25.
    PrototypeAllows you toadd new properties / methods to classHelps in implementing inheritance of sorts – you can instantiate objects of older type and then add additional properties to the “class”AdvantagesYou can add methods to “classes” you didn’t createthe functions are only stored once (in the prototype object), rather than in every new objectWhen evaluating an expression to retrieve a property, JavaScript first looks to see if the property is defined directly in the object. If it is not, it then looks at the object's prototype to see if the property is defined there. This continues up the prototype chain until reaching the root prototype
  • 26.
    Prototype exampleString.prototype.convertUnderscores =function () { return this.replace(/_/g, " "); };var underscored = "Are_there_any_spaces_in_here?";var spaced = underscored.convertUnderscores(); alert(spaced); function Bird() {this.feet = 2;this.feathers = true; return true; }var bird1 = new Bird(); alert(bird1.getFeetNum);Bird.prototype.getFeetNum = function () { return this.feet; };var bird2 = new Bird(); alert(bird2.getFeetNum());
  • 27.
    Inheritance using prototypefunctionBird() {this.feet = 2;this.feathers = true; return true; } function Canary() {this.color = "yellow"; return true; }Canary.prototype = new Bird(); //defining parent class if you willvartweety = new Canary(); alert("Feet : " + tweety.feet + " Color : " + tweety.color + " Feathers : " + tweety.feathers);function Crow() {this.superclass = Bird;this.superclass();this.color = "black"; return true; }
  • 28.
    Inheritance using prototype//define the Person Class function Person() { }Person.prototype.sayHello = function () { alert('hello'); };// define the Student classfunction Student() { }// inherit PersonStudent.prototype = new Person();// correct the constructor pointer because it points to PersonStudent.prototype.constructor = Student;// replace the sayHello methodStudent.prototype.sayHello = function () { alert('hi, I am a student'); }// add sayGoodBye methodStudent.prototype.sayGoodBye = function () { alert('goodBye'); }var student1 = new Student();student1.sayHello();student1.sayGoodBye();
  • 29.
    NamespaceNo inherent wayto prevent name conflict – if 2 people define same named “class”, the later definition will be used.Namespace is implemented by typically using domain names with the class name BUT that implies each part of the Domain Name has to be defined
  • 30.
    Namespace exampleif (typeofcom == "undefined") { com = new Object(); } if (typeofcom.qwest == "undefined") {com.qwest = new Object(); }com.qwest.Bird = function() {this.feet = 2;this.feathers = true;this.color = "yellow"; return true; } Bird = function () {this.feet = 2;this.feathers = true;this.color = "black"; return true; }
  • 31.
    ClosureClosure is aFunction instance coupled with the local variables from its environment that are necessary for its execution.How this manifests : For a function, a variable defined in its scope at the point of declaration, is carried along with the function even after the point of declaration has gone out of scope, closing the declaration$(function () {var local = 1;window.setInterval(function () { $('#display') .append('<div>At ' + new Date() + ' local=' + local + '</div>'); local++; }, 3000); });
  • 32.
    Closure contd.Another importantfeature of closures is that a function context is never included as part of the closure.this.id = 'someID';$('*').each(function(){alert(this.id);});Here this.id will give the id property for the function context of each which is NOT same as the one with someIDthis.id = 'someID';var outer = this;$('*').each(function(){alert(outer.id);});Here , the variable outer is defined in the scope of the function and hence by closure, it can access the same
  • 33.
    Unobtrusive JavaScriptWhat isit?Not a formal term but refers to an approach on how to use JavaScript in web pagesPrimarily talks about separation of behavior from presentation (sounds familiar??)<input type="text" name="date" onchange="validateDate()" />Vs.<input type="text" name="date" id="date" />$(function(){ $('#date').bind('change', validateDate);});
  • 34.
    Unobtrusive JavaScript (contd.)purposeof markup is to describe a structurecombining the structure and behavior negatively impacts maintainability inline event handlers are harder to use and maintain specially when one needs to set handlers for several events on a single element when one wants to set the same event handler on several elements when one is using event delegationIn essence, this is asking for a separate .JS file that contains all the behavior and attaches the same to markup.Typically this would result in three set of filesHtml (markup)CSS (presentation)JS (behavior)
  • 35.
    Unobtrusive JavaScript ReferenceReference :http://en.wikipedia.org/wiki/Unobtrusive_JavaScripthttp://icant.co.uk/articles/seven-rules-of-unobtrusive-javascript/http://www.onlinetools.org/articles/unobtrusivejavascript/chapter1.htmlhttp://labs.adobe.com/technologies/spry/articles/best_practices/separating_behavior.html
  • 36.
    JSON Referenceshttp://en.wikipedia.org/wiki/JSONhttp://www.json.org/http://www.hunlock.com/blogs/Mastering_JSON_(_JavaScript_Object_Notation_)http://www.jsonlint.com/ :this allows you to validate / format json stringhttps://github.com/douglascrockford/JSON-jsvarmyJSONText = JSON.stringify(myObject) varmyObject = JSON.parse(myJSONtext)http://api.jquery.com/jQuery.parseJSON/http://api.jquery.com/jQuery.getJSON/varobj = jQuery.parseJSON('{"name":"John"}'); alert( obj.name === "John" );
  • 37.
    OO Referencehttps://developer.mozilla.org/en/Introduction_to_Object-Oriented_JavaScriptPDFs fromearlier training sessions (to be shared)http://mckoss.com/jscript/object.htm : very nicely explains inheritance, polymorphism and encapsulation in JS
  • 38.