SlideShare a Scribd company logo
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

More Related Content

PDF
Oop07 6
PDF
Obvious Secrets of JavaScript
PDF
Lecture 03
PPTX
Ruby object model
PDF
The Ruby Object Model by Rafael Magana
PPTX
About Python
PPTX
javaimplementation
PDF
Cascon2011_5_rules+owl
Oop07 6
Obvious Secrets of JavaScript
Lecture 03
Ruby object model
The Ruby Object Model by Rafael Magana
About Python
javaimplementation
Cascon2011_5_rules+owl

What's hot (20)

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

Viewers also liked (20)

PDF
Introduction to JavaScript
PPTX
JavaScript and jQuery Basics
PPTX
Bootstrap PPT by Mukesh
PPTX
jQuery
PPTX
Bootstrap ppt
PPTX
jQuery Presentation
PPTX
jQuery from the very beginning
PDF
jQuery in 15 minutes
PPTX
Responsive web-design through bootstrap
PPT
Introduction to JavaScript
PPTX
jQuery PPT
PDF
jQuery for beginners
PDF
Learning jQuery in 30 minutes
PDF
Bootstrap 3 Basic - Bangkok WordPress Meetup
PPTX
Bootstrap ppt
PDF
Introduction to JavaScript
PPT
Introduction to Javascript
PPT
Javascript
PPT
Js ppt
Introduction to JavaScript
JavaScript and jQuery Basics
Bootstrap PPT by Mukesh
jQuery
Bootstrap ppt
jQuery Presentation
jQuery from the very beginning
jQuery in 15 minutes
Responsive web-design through bootstrap
Introduction to JavaScript
jQuery PPT
jQuery for beginners
Learning jQuery in 30 minutes
Bootstrap 3 Basic - Bangkok WordPress Meetup
Bootstrap ppt
Introduction to JavaScript
Introduction to Javascript
Javascript
Js ppt
Ad

Similar to Introduction To Javascript (20)

PDF
JavaScript for PHP Developers
PDF
Understanding JavaScript
PDF
A Re-Introduction to JavaScript
PDF
03 Advanced JavaScript
PPTX
The JavaScript Programming Language
KEY
Object Oriented Programming in js
PPT
Ajax and JavaScript Bootcamp
PDF
Js in the open
PDF
Tamarin and ECMAScript 4
PDF
Object-Oriented JavaScript
PPT
Javascript
PPT
Java Script Introduction
PDF
MemeScript Language
PPTX
Front end fundamentals session 1: javascript core
PDF
JavaScript Primer
PPTX
JavaScript.pptx
PDF
Javascript, Do you speak it!
PDF
JavaScript 1.5 to 2.0 (TomTom)
PDF
javascript teach
PDF
JSBootcamp_White
JavaScript for PHP Developers
Understanding JavaScript
A Re-Introduction to JavaScript
03 Advanced JavaScript
The JavaScript Programming Language
Object Oriented Programming in js
Ajax and JavaScript Bootcamp
Js in the open
Tamarin and ECMAScript 4
Object-Oriented JavaScript
Javascript
Java Script Introduction
MemeScript Language
Front end fundamentals session 1: javascript core
JavaScript Primer
JavaScript.pptx
Javascript, Do you speak it!
JavaScript 1.5 to 2.0 (TomTom)
javascript teach
JSBootcamp_White

Recently uploaded (20)

PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPTX
Cloud computing and distributed systems.
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Modernizing your data center with Dell and AMD
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Approach and Philosophy of On baking technology
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Unlocking AI with Model Context Protocol (MCP)
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Dropbox Q2 2025 Financial Results & Investor Presentation
Per capita expenditure prediction using model stacking based on satellite ima...
The Rise and Fall of 3GPP – Time for a Sabbatical?
Diabetes mellitus diagnosis method based random forest with bat algorithm
NewMind AI Weekly Chronicles - August'25 Week I
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Reach Out and Touch Someone: Haptics and Empathic Computing
Mobile App Security Testing_ A Comprehensive Guide.pdf
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Cloud computing and distributed systems.
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Modernizing your data center with Dell and AMD
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Approach and Philosophy of On baking technology
The AUB Centre for AI in Media Proposal.docx
Unlocking AI with Model Context Protocol (MCP)
“AI and Expert System Decision Support & Business Intelligence Systems”
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf

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