• Save
Javascript
Upcoming SlideShare
Loading in...5
×
 

Javascript

on

  • 958 views

 

Statistics

Views

Total Views
958
Views on SlideShare
700
Embed Views
258

Actions

Likes
5
Downloads
0
Comments
0

10 Embeds 258

http://psjplearn.blogspot.in 188
http://psjplearn.blogspot.com 60
http://psjplearn.blogspot.ca 3
http://psjplearn.blogspot.com.ar 1
http://psjplearn.blogspot.sk 1
http://psjplearn.blogspot.de 1
http://psjplearn.blogspot.cz 1
http://psjplearn.blogspot.fr 1
http://psjplearn.blogspot.tw 1
http://psjplearn.blogspot.it 1
More...

Accessibility

Categories

Upload Details

Uploaded via as OpenOffice

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Javascript Javascript Presentation Transcript

  • 1JavascriptSai PonduruParabola / IcentrisDec 2012
  • 2Book Link -http://www.syncfusion.com/resources/techportal/ebooks/javascriptThe following slides were preparedusing content from the book –“Javascript Succinctly” by CodyLindley
  • 3console.log● Firebug or Chrome Developer Tools● console.log()● typeof● jsbin.com / jsfiddle.net– 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 );
  • 4console.log (contd.)Notes:● Both Chrome & Firefox - display a functions returnvalue also
  • 5console.log (contd.)Notes:● console.log() returns undefined(only displayed in Chrome developer tools)
  • 6console.log (contd.)Notes: Can pass an object to console.log– Observe use of { } to display objects
  • 7console.log (contd.)Notes: Can pass an array to console.log– Observe use of [ ] to display arrays
  • 8Objects, Primitive ValuesAlmost everything is an objectORacts like an object.● Everything = Complex Objects +Primitive Values● Primitive Values can act like Objectsalso
  • 9Primitive values● String, Number, Boolean● Examples:5footruefalsenullundefined
  • 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 ?
  • 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.
  • 12Things to note about Primitive values (contd.)Example:var primitiveString1 = "foo";console.log(typeof primitiveString1);console.log(primitiveString1.length);console.log(typeof primitiveString1);
  • 13What are objects in Javascript ?● objects = containers for Properties– Property = name-value pair– every item in an object is a Property andnothing else
  • 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;};
  • 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.)
  • 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
  • 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 (?)
  • 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.)
  • 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
  • 20Built-In “Constructor Functions” (contd.)● Note:Object(), Array(), Function() objects● can contain other complexobjects
  • 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.●
  • 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;};
  • 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);
  • 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",...}
  • 25typeof vs .constructor● How to find out, which of the 2 methods was used tocreate a particular object ?– By checking the constructor property
  • 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!);
  • 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.)
  • 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
  • 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)
  • 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.
  • 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;
  • 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.)
  • 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/;
  • 35Value Types vs Reference Types● Primitive values – value types– Comparison is by value● Complex values – reference types– Comparison is by reference
  • 36Reference Types● Reference types examplevar original = {};//Not copied by value, just reference is copiedvar copy = original;// Manipulate the value stored in originaloriginal.foo = 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"}
  • 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.
  • 38=== operator● == operator– > comparison with type coersion=== operator– > comparison without type coersionExamples:● 0 == false // true0 === false // false, different type
  • 39=== operator (contd.)● 1 == "1" // true, auto type coercion1 === "1" // false, different type● null == undefined // truenull === undefined // false
  • 40● PART 2
  • 41Function● In Javascript, a function can be used to:– return a value– simply run some code– construct an object
  • 42Function(contd.)● Example:
  • 43Function(contd.)● Functions always return a value– If return value is not specified, undefined isreturned● Can use “return” keyword, with or without a value
  • 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
  • 45Function(contd.)● Example:
  • 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
  • 47Function(contd.)● Example:http://jsbin.com/eyeqep/1/edit
  • 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
  • 49Function(contd.)● Different ways to define a Function
  • 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
  • 51Function(contd.)● When is the difference important ?Example– http://jsfiddle.net/theacadian/G3ZXm/
  • 52Function(contd.)● Anonymous functions– function with no name– Example:● $(document).ready(function () {alert(hi);});
  • 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);
  • 54Function(contd.)● Self-invoking function expression - Example
  • 55Function(contd.)● Self-invoking anonymous function statements– Example:(function() {alert(hello world);})();
  • 56Function(contd.)● Examples Review: http://jsbin.com/egohox/1/edit
  • 57Function(contd.)Functions -– can be nested
  • 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
  • 59Function(contd.)Recursion:– Example: http://jsbin.com/acofur/1/edit
  • 60Properties● Accessing Properties● Deleting Properties● Adding Properties
  • 61Accessing properties:using “dot notation” & “bracket notation”● An objects properties can be accessedusing– “dot notation” OR– “bracket notation”
  • 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;};
  • 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;};
  • 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];
  • 65Accessing properties:using “dot notation” & “bracket notation”● “bracket notation” advantage:– useful when the property-name isan invalid Javascript identifiervar myObject = {123: zero, class: foo };
  • 66Deleting properties from objects● Deleting properties from objects ispossible● delete will not remove properties on theprototype chain
  • 67Deleting properties from objects● Deleting properties from objects ispossible● delete will not remove properties on theprototype chain
  • 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 http://javascript.crockford.com/inheritance.html)
  • 69Adding Properties● Example
  • 70Adding Properties● NOTE:– All of the native objects can be mutated(changed) also.
  • 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
  • 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
  • 73Prototype Chain,hasOwnProperty() method● We can verify the statements in the previousslide using hasOwnProperty()
  • 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
  • 75Inheritance, Prototype Chain● Example: http://jsbin.com/icigel/2/edit● Will the properties – first_name, last_name be intiger1 object ?
  • 76Inheritance, Prototype Chain● Example: http://jsbin.com/ewotap/2/edit
  • 77Inheritance, Prototype Chain● Properties that need to be inherited– Have to be added to● Tiger.prototype● And not to Tiger
  • 78Inheritance, Prototype Chain● Example 2: Adding trim() function to String() -http://kangax.github.com/es5-compat-table/
  • 79Inheritance, Prototype Chain● Example 2(contd.): adding trim() function to String()● From Kangaxs compat tables (http://kangax.github.com/es5-compat-table/) 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
  • 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
  • 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
  • 82Prototype Chain -in operator, hasOwnProperty() method● for in accesses– properties of specific object+properties in prototype chain● use hasOwnProperty to differentiate
  • 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
  • 84Head/Global object● Example 1:● Example 2:
  • 85Scope● 3 types of scope– Global– Local (or function scope)– eval
  • 86Scope (contd.)● var– Variables that are declared without var→global scope (i.e. availableeverywhere)– Varithat are declared with var→ local scope
  • 87Scope (contd.)● var & Global variablesExampleWhat is the output ?
  • 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
  • 89Scope (contd.)● No Block scope in Javascript
  • 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
  • 91Scope (contd.)ClosuresExample 1(https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Closures)
  • 92Scope (contd.)● Closures - Example 2:(https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Closures)● 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
  • 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
  • 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;}};
  • 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);
  • 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} ();} ();}}
  • 97this & prototype● When used while adding a property to .prototype,– this → instance on which property/method isinvoked
  • 98this & prototype● Example 2: Localization project relatedTo localize the strings in the below code:
  • 99this & prototype● Example 2: Localization project relatedAfter adding local tags and changing Javascript code:Code Readability is decreased ??
  • 100this & prototype● Example 2: Localization project related– If we added the below LocalValue() functionto String.prototype
  • 101this & prototype● Example 2: Localization project relatedResulting code will look like this
  • 102Inheritance● Example:– http://jsbin.com/aqicip/6/edit