SlideShare une entreprise Scribd logo
1  sur  37
Télécharger pour lire hors ligne
A Quick Intro to
                                  Javascript
                Rajat Pandit (rajat_pandit@ipcmedia.com)




Thursday, September 24, 2009                               1
Data Types
                           Object
                           Function
                           Numbers
                           Strings
                           Booleans
                           null - a value that isn’t anything
                           undefined - default value for variables
                           and parameters, value of missing members
                           in the object etc



Thursday, September 24, 2009                                          2
Objects
                       Objects can contain data and methods
                       Objects can inherit from other objects
                       An object contain an unordered
                       collection of name/value pairs
                       Values can be any type including other
                       objects
                       JSON



Thursday, September 24, 2009                                    3
Object Literals
                           Objects are wrapped in { }

                           Names can be string

                           Value can be an expression

                           ; used for separation

                           , separate pairs

                           Object literals can be used
                           anywhere a value can appear


Thursday, September 24, 2009                             4
Creating a new Object
                           new Object()
                           { } - Preferred format
                           Both are the same
                           Objects are passed by reference not by value
                           === operator compares references, not values,
                           true only if the operands are the same object

                           Members can be removed using the delete
                           operator

                           delete myobject[name];




Thursday, September 24, 2009                                               5
Object Example
                var myobject = {
                      name : “Jack Appleseed”,
                      “data”: { foo: 10, bar: 20}
                };
                var data = myobject.data;
                var foo = myobject.data.foo;




Thursday, September 24, 2009                        6
Object Augmentation
                           New members can be added to
                           any object
                           No need to define a new class

                           myobject.format.colormodel = ‘foo’;
                           myobject[another_new_member] = 34;




Thursday, September 24, 2009                                     7
Object Augmentation
                      String.prototype.trim = function() {
                      	 return this.replace(/^s*(S*(s+S+)*)s*$/,
                        "$1");
                      }

                           More on prototype in the next few
                           slides
                           Prototype library does the same
                           Very messy approach, pollutes the
                           expected behavior



Thursday, September 24, 2009                                            8
typeof Prefix Operator
                           The typeof prefix operator returns a
                           string identifying the type of value
                           Use instanceof instead   Type        typeof
                                                    object      ‘object’
                                                    function    ‘function’
                                                    array       ‘object’
                                                    number      ‘number’
                                                    string      ‘string’
                                                    boolean     ‘boolean’
                                                    null        ‘object’
                                                    undefined   ‘undefined’




Thursday, September 24, 2009                                                  9
Array
                           Array inherits from Object (like every other
                           object in JavaScript)
                           No need to provide length when creating a new
                           one
                           Unlike object they have a length member and
                           is always 1 larger than the highest subscript
                           Do not use for ... in for arrays
                           Appending new item
                           mylist[mylist.length] = ‘foo’




Thursday, September 24, 2009                                               10
Array
                        var my_array = ['abc', 'xyz', 'foo'];
                        var my_object = {foo: 10, bar:20, baz:200}

                         Array.prototype.this_is_super_lame = 'fooo';

                        for (x in my_array) {
                           console.log(x + ‘-’ + my_array[x]);
                        }

                         Output:   Output:
                         0 - abc   0 - abc
                         1 - xyz   1 - xyz
                         2 - foo   2 - foo
                                   this_is_super_lame - fooo



Thursday, September 24, 2009                                            11
Array Methods
                           concat
                           join (can also be used for concatenating multiple strings)
                           pop
                           push
                           slice
                           sort
                           splice

                           Use Objects when you think you need associative array (PHP
                           Developers) you are should be using Object not Array.




Thursday, September 24, 2009                                                            12
Checking for Array


                           value.constructor === Array

                           value instanceof Array




Thursday, September 24, 2009                             13
Function
                           They are first class Objects
                           Can be passed, stored and
                           returned just like any value
                           Inherit from object and store
                           name/value pairs
                           Function can appear anywhere
                           an expression can appear


Thursday, September 24, 2009                               14
Function Cont...
                           Functions can be contained inside other
                           functions
                           Inner function has access to the variable
                           and parameters of the function it is
                           contained within
                           This is static or lexical scoping
                           The scope that inner function has access
                           to continues even after the parent
                           function has returned. This is called
                           Closure



Thursday, September 24, 2009                                           15
Function Cont...
                           Function inside an object is
                           called a method
                           When invoked with too many
                           arguments, the rest are ignored
                           When invoked with fewer arguments,
                           the rest are set to undefined
                           No type checking


Thursday, September 24, 2009                                    16
Function Cont...
                           When a function is invoked in method
                           format, this refers to the object
                           containing it.
                           var foo = {
                              baz: 10,
                              bar: function() {
                                console.log(this.baz); // cant access baz
                                                          // directly
                              }
                           };

                           foo.bar();

                           Output
                           10



Thursday, September 24, 2009                                                17
Function Cont...
                           When object is invoked in function,
                           this refers to the global object
                               var global_variable = 5;
                               function test() {
                                 console.log(this.global_variable);
                               }
                               test();


                               Output
                               5




Thursday, September 24, 2009                                          18
Function Cont...
                           When new Function is used (implicit return is
                           optional), then this returns the new object
                           created
                               var Test = function(id) {
                                   this.something = id;
                                   this.foo = function() {
                                       console.log('this is a test: ' + this.something);
                                   }
                               }
                               var o = new Test(10),
                                        i = new Test(111);
                               o.foo();
                               i.foo();




Thursday, September 24, 2009                                                               19
Function (arguments)
                           When function is invoked, in addition
                           to its parameters it has a special
                           parameter called arguments
                           Contains all arguments from invocation
                           arguments.length will tell you how
                           many arguments were passed
                           arguments is not of type Array even
                           though it has length



Thursday, September 24, 2009                                        20
Function (arguments)
                Code:
                       var foo = function() {
                         var a = new Array();
                         console.log( typeof a );
                         console.log( typeof arguments );
                         console.log( arguments instanceof Object );
                         console.log( arguments instanceof Array );
                       }
                       foo();


                Output :
                object
                object
                true
                false




Thursday, September 24, 2009                                           21
(global) Object
                           As crockford says, the object that
                           dare not speak of its name
                           It is the container for all global
                           variables and all built in objects
                           On browsers window is the global
                           object
                           Variables defined with a var makes
                           it local to the scope


Thursday, September 24, 2009                                    22
GLOBAL VARIABLES ARE EVIL
                           Un-namespaced values can clobber
                           each others values
                           Use of it should be minimized or
                           gotten rid of totally
                           Variables defined in the
                           function / module should start
                           with var otherwise they have a
                           global scope


Thursday, September 24, 2009                                  23
Inheritance

                           OOP ensures code reuse
                           Two forms of OOP
                           - Classical
                           - Prototypal




Thursday, September 24, 2009                        24
prototype
                           JavaScript functions work as
                           methods, constructors and modules
                           It has Prototypal Inheritance,
                           instead of classical inheritance
                           This offers great expressive powers
                           All objects are directly or
                           indirectly linked to
                           Object.prototype



Thursday, September 24, 2009                                     25
prototype
                           Each object is linked to its
                           parent via a magic link
                           When a member is accessed the
                           compiler looks at the object and
                           then looks up to its parent via
                           the magic link
                           It keeps going all the way   up
                           to Object.prototype


Thursday, September 24, 2009                                  26
prototype
                    my_object = {                 my_object_parent
                        foo: 10,                  = {                          Object
                        bar:15                        bar: 10,
                                         prototype                 prototype

                               Looking for my_object.foo, found it in the object itself
                               Looking for my_object.baz looks in the object and if it
                               doesn’t find it there it goes to my_object_parent which
                               is my_object.prototype
                               Looking for my_object.some_random_member can’t find it
                               in the object, look at my_object_parent, can’t find it
                               there either, goes to Object can’t find it there and is
                               set to undefined




Thursday, September 24, 2009                                                              27
prototype
                           Augmenting the ancestor will have an
                           affect on all the children, even the
                           ones that were created before the
                           augmentation

                           Augmentation can be done via the
                           prototype property that each object
                           has




Thursday, September 24, 2009                                      28
prototype
                      var Test = function(id) {
                        this.something = id;
                        this.foo = function() {
                          console.log('this is a test: ' + this.something);
                        }
                        // implicit return not required
                      }
                      var o = new Test(10),
                          i = new Test(111);

                      o.foo();
                      i.foo();

                      Test.prototype.new_function = function() {
                        console.log('i am a new function');
                      }
                      o.new_function();



Thursday, September 24, 2009                                                  29
Prototypal Inheritance
                     var BiggerConstructor = function() {};
                     BiggerConstructor.prototype = new Test();
                     var a = new BiggerConstructor();
                     a.new_function();

                     Another way of doing Inheritance

                     function        object(o) {
                     	         function F() {};
                     	         F.prototype = o;
                     	         return new F ();
                     }



Thursday, September 24, 2009                                     30
Singleton
                           There is no need to produce a
                           class-like constructor for an
                           object that will have exactly
                           one instance
                           This is typical of JavaScript
                           applications
                           Use an object literal to get
                           started instead


Thursday, September 24, 2009                               31
Singleton
                           You have seen it before
                           The methods of a singleton can enjoy
                           access to shared private data and
                           private methods


                         var singleton = {
                             firstFunction: function(a,b) {
                             },
                             secondFunction: function(c) {
                             }
                         }




Thursday, September 24, 2009                                      32
Module Pattern
                           The methods of a singleton can enjoy
                           access to shared private datum and
                           private methods
                           Variables defined in a module are only
                           visible in a module
                           Variables defined in a function are
                           only visible to the function
                           Function can be used as module
                           containers


Thursday, September 24, 2009                                        33
Module Pattern
                        var my_module = function() {
                          var privateVariable,
                              privateFunction = function() {
                                   // stuff
                              };
                              return {
                                 firstMethod: function(a,b) {
                                   // can access privateVariable
                                   // can access privateFunction
                                 }
                              }
                        }();

                        my_module.firstMethod();




Thursday, September 24, 2009                                       34
Privileged Methods
                           Methods in the return object are
                           called Privileged methods
                           They have access to the secret
                           information
                           Has access to private variables and
                           methods
                           Obtains its secret information
                           through closure


Thursday, September 24, 2009                                     35
Power Constructor
                function PowerConstructor() {
                  var that = {},
                  privateVariable = 40;
                  that.firstMethod = function(a,b) {// private access}
                  that.secondMethod = function(c)  {// private access}
                  return that;
                }

                           Many Patterns here
                               private variables (var)
                               private methods (inner functions)
                               privileged methods (that.firstmethod)
                               no more need for use of new
                               my_object = PowerConstructor();



Thursday, September 24, 2009                                             36
Resources
                           Coding convention
                           http://javascript.crockford.com/
                           code.html
                           Linting JavaScript
                           http://jslint.org
                           Mozilla Developer Center for
                           JavaScript
                           https://developer.mozilla.org/en/
                           JavaScript


Thursday, September 24, 2009                                   37

Contenu connexe

Tendances

Google app engine cheat sheet
Google app engine cheat sheetGoogle app engine cheat sheet
Google app engine cheat sheetPiyush Mittal
 
Xml Path Language1.0
Xml Path Language1.0Xml Path Language1.0
Xml Path Language1.0LiquidHub
 
First fare 2011 frc-java-introduction
First fare 2011 frc-java-introductionFirst fare 2011 frc-java-introduction
First fare 2011 frc-java-introductionOregon FIRST Robotics
 
Dive into Python Class
Dive into Python ClassDive into Python Class
Dive into Python ClassJim Yeh
 
Prototype Utility Methods(1)
Prototype Utility Methods(1)Prototype Utility Methods(1)
Prototype Utility Methods(1)mussawir20
 
NaBL: A Meta-Language for Declarative Name Binding and Scope Rules
NaBL: A Meta-Language for Declarative Name Binding  and Scope RulesNaBL: A Meta-Language for Declarative Name Binding  and Scope Rules
NaBL: A Meta-Language for Declarative Name Binding and Scope RulesEelco Visser
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0BG Java EE Course
 
Ruby — An introduction
Ruby — An introductionRuby — An introduction
Ruby — An introductionGonçalo Silva
 
Ios development
Ios developmentIos development
Ios developmentelnaqah
 
openFrameworks freakDay S03E02 Diederick Huijbers - C++/Physics/Cloth Animati...
openFrameworks freakDay S03E02 Diederick Huijbers - C++/Physics/Cloth Animati...openFrameworks freakDay S03E02 Diederick Huijbers - C++/Physics/Cloth Animati...
openFrameworks freakDay S03E02 Diederick Huijbers - C++/Physics/Cloth Animati...roxlu
 
Collections and generic class
Collections and generic classCollections and generic class
Collections and generic classifis
 
20170113 julia’s type system and multiple dispatch
20170113 julia’s type system and multiple dispatch20170113 julia’s type system and multiple dispatch
20170113 julia’s type system and multiple dispatch岳華 杜
 

Tendances (20)

Google app engine cheat sheet
Google app engine cheat sheetGoogle app engine cheat sheet
Google app engine cheat sheet
 
8 polymorphism
8 polymorphism8 polymorphism
8 polymorphism
 
JavaScript Essentials
JavaScript EssentialsJavaScript Essentials
JavaScript Essentials
 
Xml Path Language1.0
Xml Path Language1.0Xml Path Language1.0
Xml Path Language1.0
 
First fare 2011 frc-java-introduction
First fare 2011 frc-java-introductionFirst fare 2011 frc-java-introduction
First fare 2011 frc-java-introduction
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
Core java concepts
Core    java  conceptsCore    java  concepts
Core java concepts
 
Dive into Python Class
Dive into Python ClassDive into Python Class
Dive into Python Class
 
Prototype Utility Methods(1)
Prototype Utility Methods(1)Prototype Utility Methods(1)
Prototype Utility Methods(1)
 
OO in JavaScript
OO in JavaScriptOO in JavaScript
OO in JavaScript
 
NaBL: A Meta-Language for Declarative Name Binding and Scope Rules
NaBL: A Meta-Language for Declarative Name Binding  and Scope RulesNaBL: A Meta-Language for Declarative Name Binding  and Scope Rules
NaBL: A Meta-Language for Declarative Name Binding and Scope Rules
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0
 
Ajaxworld
AjaxworldAjaxworld
Ajaxworld
 
Fast Forward To Scala
Fast Forward To ScalaFast Forward To Scala
Fast Forward To Scala
 
UML and You
UML and YouUML and You
UML and You
 
Ruby — An introduction
Ruby — An introductionRuby — An introduction
Ruby — An introduction
 
Ios development
Ios developmentIos development
Ios development
 
openFrameworks freakDay S03E02 Diederick Huijbers - C++/Physics/Cloth Animati...
openFrameworks freakDay S03E02 Diederick Huijbers - C++/Physics/Cloth Animati...openFrameworks freakDay S03E02 Diederick Huijbers - C++/Physics/Cloth Animati...
openFrameworks freakDay S03E02 Diederick Huijbers - C++/Physics/Cloth Animati...
 
Collections and generic class
Collections and generic classCollections and generic class
Collections and generic class
 
20170113 julia’s type system and multiple dispatch
20170113 julia’s type system and multiple dispatch20170113 julia’s type system and multiple dispatch
20170113 julia’s type system and multiple dispatch
 

En vedette (20)

Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
JavaScript and jQuery Basics
JavaScript and jQuery BasicsJavaScript and jQuery Basics
JavaScript and jQuery Basics
 
Bootstrap PPT by Mukesh
Bootstrap PPT by MukeshBootstrap PPT by Mukesh
Bootstrap PPT by Mukesh
 
jQuery
jQueryjQuery
jQuery
 
Bootstrap ppt
Bootstrap pptBootstrap ppt
Bootstrap ppt
 
jQuery Presentation
jQuery PresentationjQuery Presentation
jQuery Presentation
 
jQuery from the very beginning
jQuery from the very beginningjQuery from the very beginning
jQuery from the very beginning
 
jQuery in 15 minutes
jQuery in 15 minutesjQuery in 15 minutes
jQuery in 15 minutes
 
Responsive web-design through bootstrap
Responsive web-design through bootstrapResponsive web-design through bootstrap
Responsive web-design through bootstrap
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
jQuery PPT
jQuery PPTjQuery PPT
jQuery PPT
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
Learning jQuery in 30 minutes
Learning jQuery in 30 minutesLearning jQuery in 30 minutes
Learning jQuery in 30 minutes
 
Bootstrap 3 Basic - Bangkok WordPress Meetup
Bootstrap 3 Basic - Bangkok WordPress MeetupBootstrap 3 Basic - Bangkok WordPress Meetup
Bootstrap 3 Basic - Bangkok WordPress Meetup
 
Bootstrap ppt
Bootstrap pptBootstrap ppt
Bootstrap ppt
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Java script ppt
Java script pptJava script ppt
Java script ppt
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
Javascript
JavascriptJavascript
Javascript
 
Js ppt
Js pptJs ppt
Js ppt
 

Similaire à Introduction To Javascript

Understanding JavaScript
Understanding JavaScriptUnderstanding JavaScript
Understanding JavaScriptnodejsbcn
 
Javascript Objects Deep Dive
Javascript Objects Deep DiveJavascript Objects Deep Dive
Javascript Objects Deep DiveManish Jangir
 
Javascript closures
Javascript closures Javascript closures
Javascript closures VNG
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScriptJulie Iskander
 
JavaScript - Programming Languages course
JavaScript - Programming Languages course JavaScript - Programming Languages course
JavaScript - Programming Languages course yoavrubin
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScriptFu Cheng
 
Basic Mechanism of OOPL
Basic Mechanism of OOPLBasic Mechanism of OOPL
Basic Mechanism of OOPLkwatch
 
Proxies are Awesome!
Proxies are Awesome!Proxies are Awesome!
Proxies are Awesome!Brendan Eich
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced JavascriptAdieu
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascriptrelay12
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript ProgrammingSehwan Noh
 
Object Oriented Programming in JavaScript
Object Oriented Programming in JavaScriptObject Oriented Programming in JavaScript
Object Oriented Programming in JavaScriptzand3rs
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesDragos Ionita
 

Similaire à Introduction To Javascript (20)

Understanding JavaScript
Understanding JavaScriptUnderstanding JavaScript
Understanding JavaScript
 
Js: master prototypes
Js: master prototypesJs: master prototypes
Js: master prototypes
 
Javascript Objects Deep Dive
Javascript Objects Deep DiveJavascript Objects Deep Dive
Javascript Objects Deep Dive
 
Core concepts-javascript
Core concepts-javascriptCore concepts-javascript
Core concepts-javascript
 
Javascript closures
Javascript closures Javascript closures
Javascript closures
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
 
JavaScript - Programming Languages course
JavaScript - Programming Languages course JavaScript - Programming Languages course
JavaScript - Programming Languages course
 
Prototype
PrototypePrototype
Prototype
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
Basic Mechanism of OOPL
Basic Mechanism of OOPLBasic Mechanism of OOPL
Basic Mechanism of OOPL
 
Proxies are Awesome!
Proxies are Awesome!Proxies are Awesome!
Proxies are Awesome!
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
Lesson3
Lesson3Lesson3
Lesson3
 
Lesson3
Lesson3Lesson3
Lesson3
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
 
JavsScript OOP
JavsScript OOPJavsScript OOP
JavsScript OOP
 
Object Oriented Programming in JavaScript
Object Oriented Programming in JavaScriptObject Oriented Programming in JavaScript
Object Oriented Programming in JavaScript
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best Practices
 
Javascript
JavascriptJavascript
Javascript
 

Dernier

Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????blackmambaettijean
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 

Dernier (20)

Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 

Introduction To Javascript

  • 1. A Quick Intro to Javascript Rajat Pandit (rajat_pandit@ipcmedia.com) Thursday, September 24, 2009 1
  • 2. Data Types Object Function Numbers Strings Booleans null - a value that isn’t anything undefined - default value for variables and parameters, value of missing members in the object etc Thursday, September 24, 2009 2
  • 3. Objects Objects can contain data and methods Objects can inherit from other objects An object contain an unordered collection of name/value pairs Values can be any type including other objects JSON Thursday, September 24, 2009 3
  • 4. Object Literals Objects are wrapped in { } Names can be string Value can be an expression ; used for separation , separate pairs Object literals can be used anywhere a value can appear Thursday, September 24, 2009 4
  • 5. Creating a new Object new Object() { } - Preferred format Both are the same Objects are passed by reference not by value === operator compares references, not values, true only if the operands are the same object Members can be removed using the delete operator delete myobject[name]; Thursday, September 24, 2009 5
  • 6. Object Example var myobject = { name : “Jack Appleseed”, “data”: { foo: 10, bar: 20} }; var data = myobject.data; var foo = myobject.data.foo; Thursday, September 24, 2009 6
  • 7. Object Augmentation New members can be added to any object No need to define a new class myobject.format.colormodel = ‘foo’; myobject[another_new_member] = 34; Thursday, September 24, 2009 7
  • 8. Object Augmentation String.prototype.trim = function() { return this.replace(/^s*(S*(s+S+)*)s*$/, "$1"); } More on prototype in the next few slides Prototype library does the same Very messy approach, pollutes the expected behavior Thursday, September 24, 2009 8
  • 9. typeof Prefix Operator The typeof prefix operator returns a string identifying the type of value Use instanceof instead Type typeof object ‘object’ function ‘function’ array ‘object’ number ‘number’ string ‘string’ boolean ‘boolean’ null ‘object’ undefined ‘undefined’ Thursday, September 24, 2009 9
  • 10. Array Array inherits from Object (like every other object in JavaScript) No need to provide length when creating a new one Unlike object they have a length member and is always 1 larger than the highest subscript Do not use for ... in for arrays Appending new item mylist[mylist.length] = ‘foo’ Thursday, September 24, 2009 10
  • 11. Array var my_array = ['abc', 'xyz', 'foo']; var my_object = {foo: 10, bar:20, baz:200} Array.prototype.this_is_super_lame = 'fooo'; for (x in my_array) { console.log(x + ‘-’ + my_array[x]); } Output: Output: 0 - abc 0 - abc 1 - xyz 1 - xyz 2 - foo 2 - foo this_is_super_lame - fooo Thursday, September 24, 2009 11
  • 12. Array Methods concat join (can also be used for concatenating multiple strings) pop push slice sort splice Use Objects when you think you need associative array (PHP Developers) you are should be using Object not Array. Thursday, September 24, 2009 12
  • 13. Checking for Array value.constructor === Array value instanceof Array Thursday, September 24, 2009 13
  • 14. Function They are first class Objects Can be passed, stored and returned just like any value Inherit from object and store name/value pairs Function can appear anywhere an expression can appear Thursday, September 24, 2009 14
  • 15. Function Cont... Functions can be contained inside other functions Inner function has access to the variable and parameters of the function it is contained within This is static or lexical scoping The scope that inner function has access to continues even after the parent function has returned. This is called Closure Thursday, September 24, 2009 15
  • 16. Function Cont... Function inside an object is called a method When invoked with too many arguments, the rest are ignored When invoked with fewer arguments, the rest are set to undefined No type checking Thursday, September 24, 2009 16
  • 17. Function Cont... When a function is invoked in method format, this refers to the object containing it. var foo = { baz: 10, bar: function() { console.log(this.baz); // cant access baz // directly } }; foo.bar(); Output 10 Thursday, September 24, 2009 17
  • 18. Function Cont... When object is invoked in function, this refers to the global object var global_variable = 5; function test() { console.log(this.global_variable); } test(); Output 5 Thursday, September 24, 2009 18
  • 19. Function Cont... When new Function is used (implicit return is optional), then this returns the new object created var Test = function(id) { this.something = id; this.foo = function() { console.log('this is a test: ' + this.something); } } var o = new Test(10), i = new Test(111); o.foo(); i.foo(); Thursday, September 24, 2009 19
  • 20. Function (arguments) When function is invoked, in addition to its parameters it has a special parameter called arguments Contains all arguments from invocation arguments.length will tell you how many arguments were passed arguments is not of type Array even though it has length Thursday, September 24, 2009 20
  • 21. Function (arguments) Code: var foo = function() { var a = new Array(); console.log( typeof a ); console.log( typeof arguments ); console.log( arguments instanceof Object ); console.log( arguments instanceof Array ); } foo(); Output : object object true false Thursday, September 24, 2009 21
  • 22. (global) Object As crockford says, the object that dare not speak of its name It is the container for all global variables and all built in objects On browsers window is the global object Variables defined with a var makes it local to the scope Thursday, September 24, 2009 22
  • 23. GLOBAL VARIABLES ARE EVIL Un-namespaced values can clobber each others values Use of it should be minimized or gotten rid of totally Variables defined in the function / module should start with var otherwise they have a global scope Thursday, September 24, 2009 23
  • 24. Inheritance OOP ensures code reuse Two forms of OOP - Classical - Prototypal Thursday, September 24, 2009 24
  • 25. prototype JavaScript functions work as methods, constructors and modules It has Prototypal Inheritance, instead of classical inheritance This offers great expressive powers All objects are directly or indirectly linked to Object.prototype Thursday, September 24, 2009 25
  • 26. prototype Each object is linked to its parent via a magic link When a member is accessed the compiler looks at the object and then looks up to its parent via the magic link It keeps going all the way up to Object.prototype Thursday, September 24, 2009 26
  • 27. prototype my_object = { my_object_parent foo: 10, = { Object bar:15 bar: 10, prototype prototype Looking for my_object.foo, found it in the object itself Looking for my_object.baz looks in the object and if it doesn’t find it there it goes to my_object_parent which is my_object.prototype Looking for my_object.some_random_member can’t find it in the object, look at my_object_parent, can’t find it there either, goes to Object can’t find it there and is set to undefined Thursday, September 24, 2009 27
  • 28. prototype Augmenting the ancestor will have an affect on all the children, even the ones that were created before the augmentation Augmentation can be done via the prototype property that each object has Thursday, September 24, 2009 28
  • 29. prototype var Test = function(id) { this.something = id; this.foo = function() { console.log('this is a test: ' + this.something); } // implicit return not required } var o = new Test(10), i = new Test(111); o.foo(); i.foo(); Test.prototype.new_function = function() { console.log('i am a new function'); } o.new_function(); Thursday, September 24, 2009 29
  • 30. Prototypal Inheritance var BiggerConstructor = function() {}; BiggerConstructor.prototype = new Test(); var a = new BiggerConstructor(); a.new_function(); Another way of doing Inheritance function object(o) { function F() {}; F.prototype = o; return new F (); } Thursday, September 24, 2009 30
  • 31. Singleton There is no need to produce a class-like constructor for an object that will have exactly one instance This is typical of JavaScript applications Use an object literal to get started instead Thursday, September 24, 2009 31
  • 32. Singleton You have seen it before The methods of a singleton can enjoy access to shared private data and private methods var singleton = { firstFunction: function(a,b) { }, secondFunction: function(c) { } } Thursday, September 24, 2009 32
  • 33. Module Pattern The methods of a singleton can enjoy access to shared private datum and private methods Variables defined in a module are only visible in a module Variables defined in a function are only visible to the function Function can be used as module containers Thursday, September 24, 2009 33
  • 34. Module Pattern var my_module = function() { var privateVariable, privateFunction = function() { // stuff }; return { firstMethod: function(a,b) { // can access privateVariable // can access privateFunction } } }(); my_module.firstMethod(); Thursday, September 24, 2009 34
  • 35. Privileged Methods Methods in the return object are called Privileged methods They have access to the secret information Has access to private variables and methods Obtains its secret information through closure Thursday, September 24, 2009 35
  • 36. Power Constructor function PowerConstructor() { var that = {}, privateVariable = 40; that.firstMethod = function(a,b) {// private access} that.secondMethod = function(c) {// private access} return that; } Many Patterns here private variables (var) private methods (inner functions) privileged methods (that.firstmethod) no more need for use of new my_object = PowerConstructor(); Thursday, September 24, 2009 36
  • 37. Resources Coding convention http://javascript.crockford.com/ code.html Linting JavaScript http://jslint.org Mozilla Developer Center for JavaScript https://developer.mozilla.org/en/ JavaScript Thursday, September 24, 2009 37