Published on

Published in: Technology
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide


  1. 1. 1JavascriptSai PonduruParabola / IcentrisDec 2012
  2. 2. 2Book Link - following slides were preparedusing content from the book –“Javascript Succinctly” by CodyLindley
  3. 3. 3console.log● Firebug or Chrome Developer Tools● console.log()● typeof● /– console_log (seen in some slides) is afunction that I wrote when using JS Bin● Examples:var i = 5;console.log( i );console.log( typeof i );
  4. 4. 4console.log (contd.)Notes:● Both Chrome & Firefox - display a functions returnvalue also
  5. 5. 5console.log (contd.)Notes:● console.log() returns undefined(only displayed in Chrome developer tools)
  6. 6. 6console.log (contd.)Notes: Can pass an object to console.log– Observe use of { } to display objects
  7. 7. 7console.log (contd.)Notes: Can pass an array to console.log– Observe use of [ ] to display arrays
  8. 8. 8Objects, Primitive ValuesAlmost everything is an objectORacts like an object.● Everything = Complex Objects +Primitive Values● Primitive Values can act like Objectsalso
  9. 9. 9Primitive values● String, Number, Boolean● Examples:5footruefalsenullundefined
  10. 10. 10Things to note about Primitive valuesThe primitive values - String, Number, Boolean, actlike objects when used like objects// primitive valuevar primitiveString1 = "foo";console.log(primitiveString1.length);● length property is being accessed as ifprimitiveString1 is an object– How is this possible ?
  11. 11. 11Things to note about Primitive values (contd.)This is possible because -When a primitive value is used like an object:1) JavaScript converts the primitive value to an objectin order to evaluate the expression at hand.2) After expression is evaluated, Javascript converts itback to primitive value.
  12. 12. 12Things to note about Primitive values (contd.)Example:var primitiveString1 = "foo";console.log(typeof primitiveString1);console.log(primitiveString1.length);console.log(typeof primitiveString1);
  13. 13. 13What are objects in Javascript ?● objects = containers for Properties– Property = name-value pair– every item in an object is a Property andnothing else
  14. 14. 14What is a Method in Javascript ?Is it a Property also ?● Method in Javascript= Property that contains a Function() objectvar cody = new Object();cody.gender = male;cody.getGender= function() {//Function() objectreturn cody.gender;};
  15. 15. 15How to create “objects” in Javascript ?● Change in Terminology (in this book)To create objects in C#, Java– “Class”To create objects in Javascript– “Constructor-Function”OR“Object Constructor”OR“Constructor”(contd.)
  16. 16. 16How to create “objects” in Javascript ?(contd.)● Change in Terminology (in this book)In C#, Java– “Class” - template/blueprint for all objects– “constructor” - to initialize objects with someinitial valueIn Javascript– “constructor” - template/blueprint- initialization“Class” - not found anywhere in the book
  17. 17. 17Built-In “Constructor-Functions”/ “ObjectConstructors”●Examples: Object() , String()// Create Object() objectvar cody = new Object();cody.age = 33;cody.gender = male;// Create a String() object.var myString = new String(foo);● Object() - this functionality is available in C# through the “dynamic”keyword (?)
  18. 18. 18Built-In “Constructor Functions” (contd.)9 native “object constructors” / “constructorfunctions” :1) Number() - creates complex object OR primitive value2) String() - creates complex object OR primitive value3) Boolean() - creates complex object OR primitive value4) Object() - creates complex object5) Array() - creates complex object(contd.)
  19. 19. 19Built-In “Constructor Functions” (contd.)6) Function() - creates complex object7) Date() - creates complex object8) RegExp() - creates complex object9) Error() - creates complex object● MathStatic object, Example: Math.PI
  20. 20. 20Built-In “Constructor Functions” (contd.)● Note:Object(), Array(), Function() objects● can contain other complexobjects
  21. 21. 21User-Defined “Constructor-Functions”● Example:// Define Person constructor-functionvar Person = function (age, gender) {this.age = age; // observe use of thisthis.gender = gender;};// Instantiate a Person objectvar cody = new Person(33, male);● Can be used to create multiple Person()objects.●
  22. 22. 22Observation: 2 ways to create custom objects●1stway:// Using the Object() constructor.var codyA = new Object();codyA.age = 33;codyA.gender = male;codyA.getGender = function () {return codyA.gender;};
  23. 23. 23Observation: 2 ways to create custom objects●2ndway:// Using the Function() constructor.var Person = function (age, gender){this.age = age;this.gender = gender;this.getGender = function (){return this.gender;};};var codyB = new Person(33, male);
  24. 24. 24Observation: 2 ways to create custom objects● If we log both the objects – codyA & codyB,we can see that they look the sameconsole.log(codyA);// Logs : Object {age=33, gender="male",...}console.log(codyB);// Logs : Object {age=33, gender="male",...}
  25. 25. 25typeof vs .constructor● How to find out, which of the 2 methods was used tocreate a particular object ?– By checking the constructor property
  26. 26. 27new operator// new – used to create objects (like in C#, Java)var myNumber = new Number(23);var myString = new String(male);var myBoolean = new Boolean(false);var myObject = new Object();var myArray = new Array(foo, bar);var myFunction = new Function("x","y","return x*y");var myDate = new Date();var myRegExp = new RegExp(bt[a-z]+b);var myError = new Error(Darn!);
  27. 27. 28new operator & Primitive values● var myNumber = new Number(23); // An object.var myNumber = 23; // Primitive number value, notan object.● var myString = new String(male); // An object.var myString = male; // Primitive string value,not an object.● var myBoolean = new Boolean(false); // An object.var myBoolean = false; // Primitive boolean value,not an object.(contd.)
  28. 28. 29Terminology: Literal syntax● Literal syntax- what we normally use- shortcuts used for creating native objectvalues without having to use new● Can be used with Primitive Values & ComplexObjects● Examples:var s = foo; //String = Primitivevar arr = [1,2,3]; //Array = Complex Object
  29. 29. 30new operator& Literal syntax for Primitive Values● When new is Not used - no object iscreated when using primitive values .● When new is used - an object is createdeven for a Primitive Value(Example on next page)
  30. 30. 31new operator& Literal syntax for Primitive Values(contd.)Example:var s1 = "foo"; //literal syntax (primitive)var s2 = String(foo); //primitivevar s3 = new String(foo); // object// Confirm the typeof of s1, s2, s3.console.log(typeof s1, typeof s2, typeof s3);// Logs string,string,object.
  31. 31. 32new operator& Literal syntax for Primitive Values(contd.)More Examples:● var myNumber = new Number(23);var myNumberLiteral = 23;● var myString = new String(male);var myStringLiteral = male;● var myBoolean = new Boolean(false);var myBooleanLiteral = false;
  32. 32. 33new operator& Literal syntax for Non-Primitive Values● var myObject = new Object(); // using newvar myObject = {}; // literal syntax● var myArray = new Array(foo, bar);var myArray = [foo, bar];(contd.)
  33. 33. 34new operator& Literal syntax for Non-Primitive Values(contd.)● var myFunction=new Function("x","y","return x*y");var myFunction = function(x, y){return x*y};● var myRegExp = new RegExp(bt[a-z]+b);var myRegExp = /bt[a-z]+b/;
  34. 34. 35Value Types vs Reference Types● Primitive values – value types– Comparison is by value● Complex values – reference types– Comparison is by reference
  35. 35. 36Reference Types● Reference types examplevar original = {};//Not copied by value, just reference is copiedvar copy = original;// Manipulate the value stored in = bar;/* If we log original and copy, they will have a foo property because they reference thesame object. */console.log(original, copy);// Logs Object { foo="bar"} Object { foo="bar"}
  36. 36. 37Reference Types● Complex objects are equal by referencevar objectFoo = { same: same };var objectBar = { same: same };console.log(objectFoo === objectBar);// Logs false// although they are identical and of the same object type.
  37. 37. 38=== operator● == operator– > comparison with type coersion=== operator– > comparison without type coersionExamples:● 0 == false // true0 === false // false, different type
  38. 38. 39=== operator (contd.)● 1 == "1" // true, auto type coercion1 === "1" // false, different type● null == undefined // truenull === undefined // false
  39. 39. 40● PART 2
  40. 40. 41Function● In Javascript, a function can be used to:– return a value– simply run some code– construct an object
  41. 41. 42Function(contd.)● Example:
  42. 42. 43Function(contd.)● Functions always return a value– If return value is not specified, undefined isreturned● Can use “return” keyword, with or without a value
  43. 43. 44Function(contd.)Passing parameters to functions:● Can pass less parameters than function expects– parameters, for which we do not pass values,take undefined value● Can pass more parameters than function expects– extra parameter values can be accessedusing arguments array– arguments property –● an array● contains list of Passed parameters to afunction
  44. 44. 45Function(contd.)● Example:
  45. 45. 46Function(contd.)function instance length propertyvsarguments.length● function instance length property=number of parameters that function expects● arguments.length=number of parameters that were actuallypassed
  46. 46. 47Function(contd.)● Example:
  47. 47. 48Function(contd.)Functions– 1stclass citizens in Javascript●1stclass citizens =– Functions can be stored in a variable– Functions can be passed to & returned froma function– Functions can have properties
  48. 48. 49Function(contd.)● Different ways to define a Function
  49. 49. 50Function(contd.)● When is the difference important ?– function statements can be invoked beforethey are defined, but not functionexpressions– Why ?● before the code runs, functionstatements are interpreted, but notfunction expressions
  50. 50. 51Function(contd.)● When is the difference important ?Example–
  51. 51. 52Function(contd.)● Anonymous functions– function with no name– Example:● $(document).ready(function () {alert(hi);});
  52. 52. 53Function(contd.)● Self-invoking function expression– function can be invoked immediately afterdefinition using () operator– Example 1:var f = function() {alert(hello world);}();– Example 2:!function sayHi(msg) {alert(msg);}(Hi);
  53. 53. 54Function(contd.)● Self-invoking function expression - Example
  54. 54. 55Function(contd.)● Self-invoking anonymous function statements– Example:(function() {alert(hello world);})();
  55. 55. 56Function(contd.)● Examples Review:
  56. 56. 57Function(contd.)Functions -– can be nested
  57. 57. 58Function(contd.)Recursion:– A function can call itself– 2 ways to call itself● using function name● using arguments.callee()– necessary when function does nothave a name i.e. anonymousfunction
  58. 58. 59Function(contd.)Recursion:– Example:
  59. 59. 60Properties● Accessing Properties● Deleting Properties● Adding Properties
  60. 60. 61Accessing properties:using “dot notation” & “bracket notation”● An objects properties can be accessedusing– “dot notation” OR– “bracket notation”
  61. 61. 62Accessing properties:using “dot notation” & “bracket notation”● “dot notation”– Most commonly used– Example// Using “dot notation”var cody = new Object();cody.age = 33;cody.gender = male;cody.getGender = function () {return cody.gender;};
  62. 62. 63Accessing properties:using “dot notation” & “bracket notation”● “bracket notation”– Not so commonly used– Example// Using “bracket notation”var cody = new Object();cody[age] = 33;cody[gender] = male;cody[getGender] = function () {return cody.gender;};
  63. 63. 64Accessing properties:● using “dot notation” & “bracket notation”● “bracket notation” advantage:– useful when the property-name isin a variable / is computedvar cody = new Object();cody[age] = 33;cody[first_name] = cody;var propertyName = age;var ageOfCody = cody[propertyName];var s = cody[first+_+name];
  64. 64. 65Accessing properties:using “dot notation” & “bracket notation”● “bracket notation” advantage:– useful when the property-name isan invalid Javascript identifiervar myObject = {123: zero, class: foo };
  65. 65. 66Deleting properties from objects● Deleting properties from objects ispossible● delete will not remove properties on theprototype chain
  66. 66. 67Deleting properties from objects● Deleting properties from objects ispossible● delete will not remove properties on theprototype chain
  67. 67. 68Adding Properties● Classical objects are hard– not possible to add a new member to analready created object– Only way =create a new class with the newmember and then instantiate it● Javascript objects are soft & flexible– possible to add a new member to an alreadycreated object● new member can be added by simpleassignment(from Conclusion in
  68. 68. 69Adding Properties● Example
  69. 69. 70Adding Properties● NOTE:– All of the native objects can be mutated(changed) also.
  70. 70. 71Inheritance, Prototype Chain● Example 1:Suppose myArray is a Array object, and we invoketoString() method on itvar myArray = [ foo, bar ];var s = myArray.toString(); // s = foo,barSearch for toString() is done as follows :– 1st– definition of myArray is searched– 2nd– definition of Array.prototype issearched– 3rd– definition of Object.prototype issearched
  71. 71. 72Prototype Chain● Example 1: (contd.)toString() is actually defined in Array.prototype aswell as in Object.prototype, so :Search for toString() is done as follows :1st– definition of myArray is searched –– NOT FOUND2nd– definition of Array.prototype issearched– FOUND3rd– definition of Object.prototype– Search does not reach here
  72. 72. 73Prototype Chain,hasOwnProperty() method● We can verify the statements in the previousslide using hasOwnProperty()
  73. 73. 74Inheritance, Prototype Chain● Example:var Tiger = function() { }var tiger1 = new Tiger();var tiger2 = new Tiger();● To add a property that needs to be inheritedby all Tiger objects:Adding to TigervsAdding to Tiger.prototype
  74. 74. 75Inheritance, Prototype Chain● Example:● Will the properties – first_name, last_name be intiger1 object ?
  75. 75. 76Inheritance, Prototype Chain● Example:
  76. 76. 77Inheritance, Prototype Chain● Properties that need to be inherited– Have to be added to● Tiger.prototype● And not to Tiger
  77. 77. 78Inheritance, Prototype Chain● Example 2: Adding trim() function to String() -
  78. 78. 79Inheritance, Prototype Chain● Example 2(contd.): adding trim() function to String()● From Kangaxs compat tables ( on prev. slide:– Some browsers like IE 8, do not provide atrim() method for strings//below is not possible in IE 8var str = “ 123 ”.trim();– To make trim() work in IE 8 also, we usuallywrite our own method using protototype
  79. 79. 80Inheritance, Prototype Chain● Example 2 (contd.): adding trim() function to String()Search for trim() is done as follows :– 1st– definition of str is searched– NOT FOUND– 2nd– definition of String.prototype issearched– FOUND– 3rd– definition of Object.prototype● Search does not reach here
  80. 80. 81Inheritance, Prototype Chain● Example 2 (contd.): adding trim() function toString.prototypeNOTE:– Since some browsers already have trim(),and some do not,● It is better to check if trim() has alreadybeen defined or notCode from -C:wwwAscendPartitionUnityNew OfficeUSAengHTMLjsglobal.js
  81. 81. 82Prototype Chain -in operator, hasOwnProperty() method● for in accesses– properties of specific object+properties in prototype chain● use hasOwnProperty to differentiate
  82. 82. 83Head/Global object● Javascript code must be contained withinan object● In a web-browser,– Javascript code is contained &executed within window object– Hence in a web-browser:● Head object = window
  83. 83. 84Head/Global object● Example 1:● Example 2:
  84. 84. 85Scope● 3 types of scope– Global– Local (or function scope)– eval
  85. 85. 86Scope (contd.)● var– Variables that are declared without var→global scope (i.e. availableeverywhere)– Varithat are declared with var→ local scope
  86. 86. 87Scope (contd.)● var & Global variablesExampleWhat is the output ?
  87. 87. 88Scope (contd.)● var & Global variables (e.g. contd.)Variables not declared using var are added to thewindow object– s1 → available outside myFunction also– s2 → available only within myFunction
  88. 88. 89Scope (contd.)● No Block scope in Javascript
  89. 89. 90Scope (contd.)Closures● Closures– this is a language feature (like inheritance)– not a keyword– related to Scope of variables● Because Javascript implements ClosuresWhen using nested functions– inner functions have access to variables of outerfunctions
  90. 90. 91Scope (contd.)ClosuresExample 1(
  91. 91. 92Scope (contd.)● Closures - Example 2:(● To determine if a variable is available within afunction- we have to see the definitions of the parent functions also- because variables in parent functions are also available
  92. 92. 93this● RULE:– this is used inside of functions to refer tothe "parent" object that contains thefunction, except when:● using new keyword● used within Nested functions● used with .prototypeIn other words: when this appears inside a function,it does Not refer to the function itself, instead it refersto the parent of the function
  93. 93. 94this (contd.)● var cody = {age: 23,gender: male,getGender: function(){return cody.gender;}};// cody = parent object of function getGender()var cody = {age: 23,gender: male, // this = codygetGender: function(){return this.gender;}};
  94. 94. 95this (contd.)● Exception to the Rule:– when using new keyword:● this literally means the object that willbe created.var Person = function (age, gender) {this.age = age; // observe use of thisthis.gender = gender;};var cody = new Person(true, 33, male);
  95. 95. 96this (contd.)● Exception to the Rule:– if used within Nested functions:● this = window object– in browsers that do not supportECMAScript 5var myObject = {func1: function () {console.log(this); // Logs myObjectvar func2 = function () {console.log(this) // Logs windowvar func3 = function () {console.log(this); // Logs window} ();} ();}}
  96. 96. 97this & prototype● When used while adding a property to .prototype,– this → instance on which property/method isinvoked
  97. 97. 98this & prototype● Example 2: Localization project relatedTo localize the strings in the below code:
  98. 98. 99this & prototype● Example 2: Localization project relatedAfter adding local tags and changing Javascript code:Code Readability is decreased ??
  99. 99. 100this & prototype● Example 2: Localization project related– If we added the below LocalValue() functionto String.prototype
  100. 100. 101this & prototype● Example 2: Localization project relatedResulting code will look like this
  101. 101. 102Inheritance● Example:–