Javascript    Introduction      by Amit Tyagi
History   Initially LiveScript from Netscape.   JScript from Microsoft.   ECMA introduced ECMAScript for    standardize...
The Core (ECMAScript)    ECMA-262 describes it like this:    “ECMAScript can provide core scripting capabilities    for a...
The Document Object Model (DOM)   The Document Object Model (DOM) is an    application programming interface (API) for   ...
DOM<html>   <head>          <title>Sample Page</   title>   </head>   <body>          <p>Hello World!</p>   </body></html>
The Browser Object Model (BOM)   BOM deals with the browser window and    frames.   All function and properties starting...
Browser Object Model (BOM)
DOM and JS World
How to include JS in a web pageInside <script> tags       <script>              var a = 10;              alert(a);       <...
Javascript Basics
Syntax   Mostly like C and java.   Everything is case-sensitive.   Variables are loosely typed.   End-of-line semicolo...
Variables   var test = "hi“, test2, $number;   Variable declaration is optional.
Keywordsbreak      else         new      varcase       finally      return   voidcatch      for          switch   whilecon...
Reserved Wordsabstract   enum         int         shortboolean    export       interface   staticbyte       extends      l...
Statements   The if statement     –    if (condition) statement1 else statement2   do-while     –    do { statements } w...
Data types   Primitive values   Reference values
Primitive values   undefined   null   boolean   number   stringUse typeof keyword to check type of variable.
Reference Types   Classes or Object   The Object class – similar to java.lang.Object        var car = new Object();Or   ...
Memory Allocation
Classes and objects injavascript   No class keyword available, instead    constructor function works as class definition....
Builtin ObjectsObject        Function    Array        StringBoolean       Number      Date         RegExpError         Eva...
Function defination     function showInfo(a) {          alert(a);     }     var showInfo = function(a){ alert(a);}     var...
Functions ( contd.)   Functions are also object, in fact everything    is an object in JavaScript   Functions can return...
Functions scopeBy default in window scopethis points to current object’s scope, defaultsto windowCan be altered using call...
Using function as Classvar Policy = function(name) {                  this.policyName = name;            }var pol1 = new P...
Variables scope1.   Start from local scope and ends till global     scope.
Prototype propertyEvery function has a prototype propertyEvery object’s scope chain fall backs to constructorfunction’s pr...
Prototype
Prototype facts   Prototype object is common across all    instances of the function( class)   Prototype is dynamic, any...
__proto__ and constructorvar func = function() { }func.prototype.a = 10;var obj = new func();obj.a; // 10obj.__proto__.a ;...
Using prototype to create classvar funcA = function() {this.a = 10;}funcA.prototype.b = 20;funcA.prototype.doSomething = f...
Prototype chainingvar A = function(){};var B = function(){};B.prototype = new A();B.prototype.constructor= B;var X = new B...
JSONJavaScript Object NotationArray []Object {“key”:”value, ….}var obj = {};obj.a = 10;obj.doSomething = function(){};
Using JSON to create object andclassvar myClass = function (arg1) {            var _property1 = 20;            var _method...
AJAXAsynchronous JavaScript And ( Advanced)XMLXMLHttpRequest Object
AJAX Request
XMLHttpRequest – cross browser Supportif (typeof XMLHttpRequest == "undefined") { XMLHttpRequest = function () {  try { re...
Ajax examplevar xhr = new XMLHttpRequest();xhr.onreadystatechange = function() {  if(xhr.readyState == 4){alert(xhr. respo...
Event HandlingEvent propagation and event Bubbling                        IE only support event                        bub...
Adding event HandlersMozilla compatible browsers[elementObject].addEventListener(“event_handler”, handlerFunction, boolCap...
Timing functionssetTimeout– calls only oncevar timeoutVar =setTimeout( function_to_call,milliseconds);clearTimeout(timeout...
DOM APIdocument.getElementByIddocument.getElementsByTagNamedocument.createElementdocument.appendChildelementObject.innerHTML
Introduction to Javascript
Introduction to Javascript
Introduction to Javascript
Introduction to Javascript
Upcoming SlideShare
Loading in...5
×

Introduction to Javascript

2,948

Published on

Video links: Part 1 : http://www.youtube.com/watch?v=lWSV4JLLJ8E Part2 : http://www.youtube.com/watch?v=-MvSBqPlMdY

Published in: Technology
0 Comments
10 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
2,948
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
186
Comments
0
Likes
10
Embeds 0
No embeds

No notes for slide

Introduction to Javascript

  1. 1. Javascript Introduction by Amit Tyagi
  2. 2. What Is JavaScript? Executes in Host Environment ( mostly Browser). Interpreted language. Major use cases are: a. making web pages dynamic (animations, RICH UI) b. form validation c. background communication with server (AJAX) etc. d. ….
  3. 3. History Initially LiveScript from Netscape. JScript from Microsoft. ECMA introduced ECMAScript for standardized Scripting language. Current Version is 5.1 of ECMA-262.
  4. 4. The Core (ECMAScript) ECMA-262 describes it like this: “ECMAScript can provide core scripting capabilities for a variety of host environments, and therefore the core scripting language is specified...apart from any particular host environment.” ECMAScript | ---------------------------------------- | | | JavaScript Actionscript ScriptEase
  5. 5. The Document Object Model (DOM) The Document Object Model (DOM) is an application programming interface (API) for HTML as well as XML.
  6. 6. DOM<html> <head> <title>Sample Page</ title> </head> <body> <p>Hello World!</p> </body></html>
  7. 7. The Browser Object Model (BOM) BOM deals with the browser window and frames. All function and properties starting inside window object. Internet Explorer extends the BOM to include the ActiveXObject class, which can be used to instantiate ActiveX objects through JavaScript.
  8. 8. Browser Object Model (BOM)
  9. 9. DOM and JS World
  10. 10. How to include JS in a web pageInside <script> tags <script> var a = 10; alert(a); </script>Within external file <script src=“page.js“type=“text/javascript” ></script>
  11. 11. Javascript Basics
  12. 12. Syntax Mostly like C and java. Everything is case-sensitive. Variables are loosely typed. End-of-line semicolons are optional. Comments are the same as in Java, C, and Perl.
  13. 13. Variables var test = "hi“, test2, $number; Variable declaration is optional.
  14. 14. Keywordsbreak else new varcase finally return voidcatch for switch whilecontinue function this withdefault if throwdelete in trydo instanceof typeof
  15. 15. Reserved Wordsabstract enum int shortboolean export interface staticbyte extends long superchar final native synchronizedclass float package throwsconst goto private transientdebugger implements protected volatiledouble import public
  16. 16. Statements The if statement – if (condition) statement1 else statement2 do-while – do { statements } while (condition ) While – while (condition) { statements} for – for (initialization; condition; post-loop-expression) { statements} for-in for (property in expression) {statements}
  17. 17. Data types Primitive values Reference values
  18. 18. Primitive values undefined null boolean number stringUse typeof keyword to check type of variable.
  19. 19. Reference Types Classes or Object The Object class – similar to java.lang.Object var car = new Object();Or var myClass = function(){}; var myObject = new myClass();Or JSON way var myObject = {};
  20. 20. Memory Allocation
  21. 21. Classes and objects injavascript No class keyword available, instead constructor function works as class definition. Classes and objects are dynamic, can be altered at runtime.
  22. 22. Builtin ObjectsObject Function Array StringBoolean Number Date RegExpError EvalError RangeError ReferenceErrorSyntaxError TypeError URIError
  23. 23. Function defination function showInfo(a) { alert(a); } var showInfo = function(a){ alert(a);} var showInfo = new Function(“a”,“alert(a)”);
  24. 24. Functions ( contd.) Functions are also object, in fact everything is an object in JavaScript Functions can return any data type, ‘undefined’ if none specified.
  25. 25. Functions scopeBy default in window scopethis points to current object’s scope, defaultsto windowCan be altered using call and apply method func.call(any_scope, [arg1,arg2, ..]); func.apply(any_scope, arg1,arg2,..);
  26. 26. Using function as Classvar Policy = function(name) { this.policyName = name; }var pol1 = new Policy(“AccessPolicy”);var pol2 = new Policy(“AuthenticationPolicy”);console.log(pol1.policyName); // AccessPolicyconsole.log(pol2.policyName); //AuthenticationPolicy
  27. 27. Variables scope1. Start from local scope and ends till global scope.
  28. 28. function closures
  29. 29. Prototype propertyEvery function has a prototype propertyEvery object’s scope chain fall backs to constructorfunction’s prototype.var func = function() {this.a=10; }func.prototype.a = 20;var obj = new func();console.log(obj.a); // 10delete obj.a;console.log(obj.a); // 20
  30. 30. Prototype
  31. 31. Prototype facts Prototype object is common across all instances of the function( class) Prototype is dynamic, any changes made in prototype gets reflected in all object instances instantly.
  32. 32. __proto__ and constructorvar func = function() { }func.prototype.a = 10;var obj = new func();obj.a; // 10obj.__proto__.a ; // 10obj.constructor.prototype.a; // a
  33. 33. Using prototype to create classvar funcA = function() {this.a = 10;}funcA.prototype.b = 20;funcA.prototype.doSomething = function(){ }var objA = new funcA();funcA.prototype.c = 30;console.log(objA);
  34. 34. Prototype chainingvar A = function(){};var B = function(){};B.prototype = new A();B.prototype.constructor= B;var X = new B();
  35. 35. JSONJavaScript Object NotationArray []Object {“key”:”value, ….}var obj = {};obj.a = 10;obj.doSomething = function(){};
  36. 36. Using JSON to create object andclassvar myClass = function (arg1) { var _property1 = 20; var _method = function() {}; return { public_property:arg1, public_method:function() { _method(); } };}var myObject = new myClass(10);
  37. 37. AJAXAsynchronous JavaScript And ( Advanced)XMLXMLHttpRequest Object
  38. 38. AJAX Request
  39. 39. XMLHttpRequest – cross browser Supportif (typeof XMLHttpRequest == "undefined") { XMLHttpRequest = function () { try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch(e) {} try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch(e) {} try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} throw new Error("This browser does not support
  40. 40. Ajax examplevar xhr = new XMLHttpRequest();xhr.onreadystatechange = function() { if(xhr.readyState == 4){alert(xhr. responseText); } };xhr.open("GET","page.xml",true);xhr.send(null);
  41. 41. Event HandlingEvent propagation and event Bubbling IE only support event bubbling
  42. 42. Adding event HandlersMozilla compatible browsers[elementObject].addEventListener(“event_handler”, handlerFunction, boolCapture);[elementObject].removeEventListener(“event_handler”, handlerFunction,boolCapture);IE[elementObject].attachEvent(“event_handler”, handlerFunction);[elementObject].detachEvent(“event_handler”, handlerFunction);
  43. 43. Timing functionssetTimeout– calls only oncevar timeoutVar =setTimeout( function_to_call,milliseconds);clearTimeout(timeoutVar);setInterval – calls repeatedlyvar intervalVar =setInterval( function_to_call,milliseconds);clearInterval(intervalVar);
  44. 44. DOM APIdocument.getElementByIddocument.getElementsByTagNamedocument.createElementdocument.appendChildelementObject.innerHTML

×