You are on page 1of 23

Javascript Essentials

a Keyhole Software tutorial


This tutorial covers:
JavaScript Execution Environment
The structure of the JavaScript language
The importance of Objects
Prototypes and Inheritance
unctions and !losures
"J"#
If you$ve been developing enterprise %eb applications& it$s li'ely that you have applied JavaScript in some
fashion ( probably to validate user input %ith a JavaScript function that validates a form control& manipulate
an )T*+ document object model ,-O*. for a user interface effect& or even to use "J"# to access the server
to eliminate a page refresh/
Single Page "pplication architectures allo% rich& responsive application user interfaces to be developed/
There are many frame%or's and approaches available& excluding plug(in technologies& that are JavaScript(
based/ This means that developers need a deeper understanding of the JavaScript language features/ This
tutorial assumes you have programming experience in a traditional object oriented language li'e Java or !0&
and introduces features of JavaScript that allo%s it to be a general purpose programming language/ 1ou may
be surprised by its expressiveness and object oriented capabilities/
Page 2 of 34
5eyhole Soft%are& ++!/ 6788 State +ine 9oad& Suite :;; +ea%ood& 5S <<38< Tel 6==(;32(==<7 %%%/'eyholesoft%are/com
!opyright > 3824 5eyhole Soft%are& ++!/ "ll rights reserved/
TABLE OF CONTENTS
1. Environment ................................................................. 3
Open Source Steps ?p ////////////////////////////////////////////////////////////////////////////4
2. Modularity / Structure .................................................. 4
*emory ////////////////////////////////////////////////////////////////////////////////////////////////:
Global Variables ////////////////////////////////////////////////////////////////////////////////:
@hitespace and Semicolons /////////////////////////////////////////////////////////////////////;
!omments ////////////////////////////////////////////////////////////////////////////////////////////;
"rithmetic Operators //////////////////////////////////////////////////////////////////////////////;
AA and AAA /////////////////////////////////////////////////////////////////////////////////////////<
lo% !ontrol //////////////////////////////////////////////////////////////////////////////////////////<
!ode Bloc's /////////////////////////////////////////////////////////////////////////////////////////<
Scope //////////////////////////////////////////////////////////////////////////////////////////////=
"*-C!ommonJS *odule Specifications ///////////////////////////////////////////////////// =
3. Data Types ................................................................. 7
Primitive ///////////////////////////////////////////////////////////////////////////////////////////////6
"rrays //////////////////////////////////////////////////////////////////////////////////////////////////6
"rray Operations ////////////////////////////////////////////////////////////////////////////////////6
?ndefined and Dull E///////////////////////////////////////////////////////////////////////////////7
4. O!ects..........................................................................
"
Built(In Objects ///////////////////////////////////////////////////////////////////////////////////// 28
!reating Objects ////////////////////////////////////////////////////////////////////////////////////28
Literal Objects //////////////////////////////////////////////////////////////////////////////////28
Constructor Function Objects ///////////////////////////////////////////////////////////// 23
Prototypes ............................................................................................23
Prototype Chaining / Inheritance ........................................................ 24
Prototypes in Action Ipleenting the singleton pattern......................2:
#. $unctions...................................................................... 1#
"nonymousC!losures //////////////////////////////////////////////////////////////////////////////2<
*emoiFing ////////////////////////////////////////////////////////////////////////////////////////////2<
Execution !ontext ////////////////////////////////////////////////////////////////////////////////// 2=
unction !losures in "ction and *odularity Support //////////////////////////////////// 26
-ependency Injection /////////////////////////////////////////////////////////////////////////////38
%. E&ceptions/Errors......................................................... 2'
"J"# ////////////////////////////////////////////////////////////////////////////////////////////////////32
7. Summary....................................................................... 22
Page 3 of 34
5eyhole Soft%are& ++!/ 6788 State +ine 9oad& Suite :;; +ea%ood& 5S <<38< Tel 6==(;32(==<7 %%%/'eyholesoft%are/com
!opyright > 3824 5eyhole Soft%are& ++!/ "ll rights reserved/
1. ENVIRONMENT
One clue that JavaScript %as not originally intended to be a general purpose language is the fact that a
bro%ser is reGuired to execute it/ The snippet belo% sho%s ho% an )T*+ page loads a JavaScript function
defined inline/ Dormally this assumes the )T*+ page and JavaScript file reside on a %eb server/
Listing 1 TML page l!a"ing a JavaScript #$ncti!n
<script>
function sayhello() {
alert('hello world');
}
</script>
...
<input type=button alue=say hello onclic!=sayhello();/>
The sayhello()function defined above can invo'ed and executed in a variety of %ays& including:
2/ Putting inline JavaScript tags at the beginning or end of the file %hen the )T*+ form button is
clic'ed/
3/ !alling the function %hen a form button is clic'ed/
4/ Putting <script> </script> elements at the beginning or end of an )T*+ document& depending on
the bro%ser you$re using/
:/ Executing JavaScript on a page load using the jHuery frame%or'/
"s you can see& there is not any 'ind of main method or entry point mechanism li'e other languages& so a
bro%ser and an )T*+ page load of some 'ind is reGuired to execute JavaScript/ Some server side Java
solutions have recently become available& but generally spea'ing JavaScript for ?I development reGuires a
bro%ser/
Open S!$rce Steps %p
+uc'ily& innovations of the open source community have filled this need/ Environments have been created
that allo% JavaScript to be executed outside of a bro%ser& commonly referred to as Iheadless&J or server side
JavaScript/
Dode/js is one popular open source frame%or' that provides a JavaScript runtime environment outside of
a bro%ser/ @ith Dode/js& JavaScript can be executed from a command line or by specifying files/ Dode/js is
also available for most operating systems/ Phantom/js is another viable option on the mar'et/ "lthough
similar& the intent of the headless environments is different bet%een the t%o/ Phantom/js has )T*+ -O*
,-ocument Object *odel. available %hile Dode/js does not/ But both still provide a %ay to develop and test
code outside of a bro%ser and %eb server/ )ere are lin's to these projects:
Dode K http:CCnodejs/orgC
Phantom K http:CCphantomjs/orgC
The examples presented in this tutorial can all be typed into and executed %ith a headless JavaScript
environment/ "ssuming Dode/js or Phantom/js binaries have been installed on your operating system& you
can execute the previous JavaScript file %ith the expressions that follo%:
Page 4 of 34
5eyhole Soft%are& ++!/ 6788 State +ine 9oad& Suite :;; +ea%ood& 5S <<38< Tel 6==(;32(==<7 %%%/'eyholesoft%are/com
!opyright > 3824 5eyhole Soft%are& ++!/ "ll rights reserved/
// "aa #cript defined // $%ecutin& with a node console
// in 'ello(orld.)s te%t file
function hello(orld() {
console.lo&(*hello world)
}
hello(orld();
// $%ecute "aa#cript
+node helloworld.)s
+phanto,)s helloworld.)s
Figure 1 Executing JavaScript from the
command line
&. MO'%LARIT()STR%CT%RE
JavaScript does not have a lot of structural elements li'e other languages/ Part of this is due to its original
origins as a dynamic prototype(based language/ *odularity is accomplished by partitioning JavaScript
functionality into separate files/ Typically JavaScript libraries are defined in one giant file %hich can be painful
to maintain and comprehend/
?pcoming tutorials %ill present modularity %or'arounds that are necessary for developing large
applications %ith JavaScript& but it is still important to understand primitive JavaScript to establish a
foundation of understanding/
Me*!r+
+i'e other object oriented languages& developers don$t specifically need to %orry about or perform allocation
and deallocation of memory/ Since everything is an object that is dynamically created& the runtime
environment %ill utiliFe a garbage collection mechanism to reclaim objects that are no longer visible or
reachable by the current execution context/
In theory& developers should not to %orry about memory reclaiming or lea's/ )o%ever& there are %ays
that object references become Fombied or unreachable by the garbage collector/ !losures are one %ay object
references can become unreachable causing a memory lea'/
,LOBAL VARIABLES
@hen a page %ith JavaScript is loaded& objects and variables created and defined %ith the page consume
memory/ The garbage collector %ill trac' and reclaim memory by objects that are no longer referenced by
anything/ )o%ever there is a %ay for global objects to be defined that is visible during the lifetime of the
bro%ser executable that JavaScript is executing %ithin/ " runtime %indo% variable is visible that references a
globally available object/ 1ou can freely addCattach objects to the %indo% variable/ The follo%ing code sho%s
an example of a global variable definition/
window.user-d = .)doe.; / Global Variable

ar user-d = .)doe; / Local Variable
It$s important to note that if you define a variable %ithout L"9& then it$s attached to the global %indo%
object/ The follo%ing code sho%s this:
user-d = .)doe.; / Attached to Window
BEST -RACTICE. 1ou should rarely need to define global variables by attaching to the %indo% property/ or a
Single Page "pplication& most frame%or's %ill provide a pattern for defining global objects/
Page : of 34
5eyhole Soft%are& ++!/ 6788 State +ine 9oad& Suite :;; +ea%ood& 5S <<38< Tel 6==(;32(==<7 %%%/'eyholesoft%are/com
!opyright > 3824 5eyhole Soft%are& ++!/ "ll rights reserved/
/0itespace an" Se*ic!l!ns
Previous tutorials have described the origins of JavaScript and pointed out its features as a dynamic object(
based language/ The name IJavaScriptJ li'ely came to be due the similarity %ith the Java syntax/ +i'e Java&
JavaScript syntax is simple& free form& and case sensitive/ Expressions are terminated %ith a semicolons/
Listing & An e1a*ple !# JavaScript s+nta1
ar abc = 'a' 0 'b' 0 'c';
ar def =
'd' 0
'e' 0
'f';
console.lo&(abc 0 def);
Semicolons are reGuired to terminate expressions& but JavaScript cuts slac' to laFy developers %ho forget
to terminate their expressions %ith semicolons/ )o%ever& it$s best practice to al%ays terminate expressions
%ith a semicolon/
C!**ents
!omments are non executable lines of code that can be applied to help document your code/ Bloc' and line
comments can be defined/
/1
2loc! co,,ents
1/
...
// line co,,ents
...
ar a = .abc.; // end of line co,,ent
Arit0*etic Operat!rs
"vailable operators are as you %ould expect for arithmetic operations ,M& (& C& N./ The M is overloaded to
support string concatenation/ ?nary increment and decrement operators are supported in the same fashion
as !& !0& and Java/ +isting 4 sho%s some example operators in action/
Listing 2 An e1a*ple !# arit0*etic !perat!rs
ar count = 3; / Increment/decrement
console.lo&( 44count ); // lo&s 5
console.lo&( 00count ); // lo&s 3
console.lo&( count44 ); // lo&s 5
console.lo&( count00 ); // lo&s 3
ar % = 3; / Assignment
ar y0= 3; // y = 67;
ar y4= 3; // y = 3;
ar y1= 3; // y = 83;
ar y/= 3; // y = 3;
ar s6 = .hello.; / String Concatenation
ar s8 = .world.;
ar s9 = s6 0 s8;
Page ; of 34
5eyhole Soft%are& ++!/ 6788 State +ine 9oad& Suite :;; +ea%ood& 5S <<38< Tel 6==(;32(==<7 %%%/'eyholesoft%are/com
!opyright > 3824 5eyhole Soft%are& ++!/ "ll rights reserved/
33 an" 333
The assignment operation AA is used for eGuality chec's/ It %ill perform type conversions before chec'ing
eGuality/ JavaScript also introduces the AAA operator %hich chec's for eGuality/ It %ill not perform type
conversion/ Study the expressions in listing : belo% and you$ll see this nuance/
Listing 4 An e1a*ple !# 33
console.lo&( 7 == '' ); / logs true, performs type conersion
console.lo&( 7 === '' ); / logs false, no type conersion
console.lo& ( 3 == '3'); / logs true, performs type conersion
console.lo& ( 3 === '3'); / logs false, no type conersion
console.lo& ( true == '6'); / logs true, performs type conersion
console.lo& ( true === '6'); / logs false, no type conersion!
BEST -RACTICE. or safeness& al%ays use the AAA for eGuality chec's/
Fl!5 C!ntr!l
Execution paths are controlled using ifCelse and looping commands/ They are fairly straight for%ard& basically
the same as you have used in almost all languages/
Listing 6 An e1a*ple !# e1ec$ti!n pat0 c!ntr!l
ar list = :6;8;9;5;3<;
for (ite, in list) { / "or Loop
console.lo&(ite,);
}
for each (ite, in list) { / Same as for, deprecated, don#t use
console.lo&(ite,);
}
for (ar i=7;i<list.len&th;i00)
{
console.lo&(list:i<); / "or loop with inde$
}
if (6 0 6 == 8 ) { / if/else
console.lo&(.=he world ,a!es sense....);
} else {
console.lo&(.=he chaos ensues....);
}

ar count = 67;
while (count > 7) { / %o Loop
console.lo&(.>ount = .0count44);
}
C!"e Bl!c7s
JavaScript expressions can be enclosed code bloc's that can be attached to function definitions or defined to
delineate conditional and looping expressions/ !ode bloc's are defined using OP characters/
function() {...}
-f/$lse
if (<condition>) {...}
?or @oop
for (< e%pression>) {A}
Page < of 34
5eyhole Soft%are& ++!/ 6788 State +ine 9oad& Suite :;; +ea%ood& 5S <<38< Tel 6==(;32(==<7 %%%/'eyholesoft%are/com
!opyright > 3824 5eyhole Soft%are& ++!/ "ll rights reserved/
SCO-E
Scoping around code bloc's %ith JavaScripts differs from %hat you %ould expect %ith other languages/
Lariables defined %ithin conditional and looping constructs are not locally scoped to an enclosing code bloc'/
This is important to understand in order to prevent possible side effects/
@hat %ould you expect the console output to be if the expressions that follo% are executedQ
ar a = 'abc';
if (true) {
ar a = 'def';
}
console.lo&(a);
1ou may be surprised to 'no% the output %ould be def& and not abc. The variable defined in the
conditional code bloc' overrides the outer variable definitions/ Scoping behavior %ithin function code bloc's
behaves as you %ould expect/
)ere is another example/ @hat %ould you expect the console output to be %hen these expressions are
executedQ
ar a = 'abc';
function s() {
ar a = 'def';
}
s(); B
console.lo&(a); / &$ecute function
Lariable a is visible and scoped to function s()/ So the log output %ould be abc;. -id you ans%er it
correctlyQ
AM')C!**!nJS M!"$le Speci#icati!ns
Efforts have been made to ma'e JavaScript a viable server side language/ *odularity %as one area that
needed to be addressed& so open source projects created a common module "PI/ One popular open source
project is commonJs/org %hich defines an "PI for defining module and dependencies/ "nother popular
module "PI is "*-& %hich stands for "synchronous *odule -efinition/ Both have their advantages/
9eGuire/js implements the "*- specification/ +oading JavaScript modules asynchronously& instead of
synchronously& allo%s modules to be loaded in an on(demand manner& and helps %ith performance&
debugging an other issues& especially in the bro%ser environment/
The module pattern sho%n in this section is essentially part of the implementation for used for the
specifications/ So& in practice you should use an existing proven module dependency frame%or' to support
your SP"& but having some understanding of %hat is going on under the covers is helpful/
2. 'ATA T(-ES
JavaScript has a dynamic type system/ This is in contrast to static type languages such a Java and !0& %hich
reGuire data variables to be typed/ @hile this provides type safeness and arguably soft%are that is easier to
maintain& it also reGuires a compilation step& %here JavaScript does not& as expressions are interpreted at
runtime/ There is much debate in the IT community regarding the agility and flexibility of dynamic versus
typed languages/ Both offer advantages& so you %ill have to ma'e your o%n decisions on this debate/
Page = of 34
5eyhole Soft%are& ++!/ 6788 State +ine 9oad& Suite :;; +ea%ood& 5S <<38< Tel 6==(;32(==<7 %%%/'eyholesoft%are/com
!opyright > 3824 5eyhole Soft%are& ++!/ "ll rights reserved/
-ri*itive
+i'e other object languages& JavaScript provides built(in system primitive types/ Primitive types exist for
performance& but some primitive types are also defined as objects %hich allo% method calls and can be
extended/ +i'e classical languages such as !0 and Java& primitive types are passed by value instead of by
reference/ Since primitive types are typical to most languages& the expression in listing < should provide
enough usage information/
Listing 8 E1a*ple -ri*itive 'ata T+pes
ar i = 677;f = 677.67; / 'umbers, stored as () bit base *+ floating point
ar s = 3.CDe85; / Very large or small number scientific notation
ar s = .hello (orld.; / String, double or single ,uotes
ar b = true; / -oolean
BEST -RACTICE. ?se a *ath library %hen arithmetic values need to be exact/ JavaScriptRs float has issues
,e/g/ 8/2 M 8/3 A 8/4888888888:. and inexactness in enterprise applications is problematic/
Arra+s
"rrays can be created literally or using a constructor approach/ +i'e other languages they are Fero(based/
"lso& since JavaScript is dynamic& initial siFe does not have to be declared/ They just have to be defined/
+isting = sho%s some implementation examples:
Listing 9 Arra+ i*ple*entati!n e1a*ple
ar states = :'!s';',o';'ne';'co'<;
console.lo&(states);
ar countries =
countries:7< = .Enited #tates.;
countries:6< = .>anada.;
console.lo&(countries);
ar ,i%ed = :'te%t';true;67.77<;
console.lo&(,i%ed);
Arra+ Operati!ns
Besides containing a list of data objects& arrays have methods defined to help manipulate and iterate over
their contents/ There many methods/ +isting 6 sho%s some interesting ones and ho% you can iterate over
them:
Listing : Arra+ !perati!ns
ar a = :'!s';',o';'ne';'co'<;
ar b = :'aF';'o!';'t%'<;
console.lo&( a.concat(b) ); / 'ew array concatenated
console.lo&( a.)oin(b) ); / .oins arrays into a string
a.push(',e'); / /ush elements to end of array, returns length
console.lo&( a.pop() ); / 0emoes element from end of array and returns it
for (ar ele in a) { / Loop oer array
console.lo&(ele);
}
Page 6 of 34
5eyhole Soft%are& ++!/ 6788 State +ine 9oad& Suite :;; +ea%ood& 5S <<38< Tel 6==(;32(==<7 %%%/'eyholesoft%are/com
!opyright > 3824 5eyhole Soft%are& ++!/ "ll rights reserved/
%n"e#ine" an" N$ll
JavaScript introduces a Inot definedJ data type/ This is not to be confused %ith a null value& as they are not
the same/ "gain& compiled languages do not need an undefined distinction& since anything not defined %ill
result in a compilation error/ ?ndefined data types are set to variables that do not have a value assigned/ The
null data type represents a value of null/ The snippet belo% illustrates the differences:
ar ;
console.lo&(); / 1ndefined
ar = null;
console.lo&(); / 'ull
?ndefined and null causes confusion as many assume that variables and object properties are
automatically assigned a null value %hen defined/ The example above sho%s that they are assigned an
undefined value or type/ Since undefined eGuals nothing& JavaScript provides a shortcut mechanism to chec'
for undefined variables& as %ith the expression belo%/ This %or's for undefined and null/
ar ;
if () {console.lo&{true)} / true
ar = null;
if () console.lo&(true); / true
Since undefined is assigned by default& it$s safer to use the shortcut method to chec' for empty data values&
instead of doing null chec's& as sho%n belo%:
ar = null;
if ( == null) { console.lo&(*alue is null); }
@hy& %ell %hat happens if the developer forgets to initialiFe a data value %ith nullQ " bug in logic could occur/
BEST -RACTICE. -on$t initialiFe your variables and properties %ith null/ 9ely upon JavaScript undefined
default and perform chec's using the if(alue) default value/
4. OBJECTS
Everything in JavaScript is an object/ Strings& Dumbers& "rrays& and even functions& are objects that have
properties and methods/ System objects supplied by the runtime environment implements objects for
primitive types/ They are sometimes called I%rapper objects&J as they %rapper their respective primitive data
types/
)ere are some expressions that send methods calls to some high level primitive objects supplied:
ar s = 'hello world'; / String
console.lo&(s.len&th); / 'umber, %isplays **
ar a,ount = 677.68953; / 'umber
console.lo&(a,ount.to?i%ed(8)); / 'umber, %isplays *++!*2
+i'e object oriented languages& JavaScript also has a ne% operator/ It can be used to create primitive
object instances/
+isting 7 ,located on page 28. sho%s some examples using the ne% operator/ There$s more about the ne%
operator further along in this tutorial& so stay tuned/
Page 7 of 34
5eyhole Soft%are& ++!/ 6788 State +ine 9oad& Suite :;; +ea%ood& 5S <<38< Tel 6==(;32(==<7 %%%/'eyholesoft%are/com
!opyright > 3824 5eyhole Soft%are& ++!/ "ll rights reserved/
Listing ; Ne5 !perat!rs in JavaScript
ar s = 'hello world' / String
console.lo&(s.len&th); / %isplays **
ar a,ount = 677.68953; / 'umber
console.lo&(a,ount.to?i%ed(8)); / %isplays *++!*2

ar s = new #trin&('hello world'); / String 3b4ect
console.lo&(s.len&th); / %isplays **
ar a,ount = new Gu,ber(677.68953); / 'umber 3b4ect
console.lo&(a,ount.to?i%ed(8)); / %isplays *++!*2
ar d = new Hate(); / %ate 3b4ect
console.lo&(d.&etIonth()); / %isplays current date month 5+6**7
B$ilt<In O=>ects
Everything in JavaScript is an object provided by the JavaScript runtime environment/ )ere is a list of
available object types:
String K "rray of character values
Boolean K !onditional trueCfalse
-ate ( 9epresents date time value
Dumber K 9epresents all integral and floating point numeric values
*ath K Provides methods for mathematical functions such as abs& log& tan& etc/
unction K Executable bloc' of code that can accept parameters and return a value
Object K Base object prototype for all objects
9egExp K Perform pattern matching& search& and replace on strings
1ou$ve already seen ho% some of these objects are used for primitive data types and arrays/ @hat may
not be obvious is that functions are also objects& or Ifirst(class objects&J meaning function objects can be
created using JavaScript syntax/ *ore details about function objects are coming up& but first let$s jump into
some details about JavaScript objects/
Creating O=>ects
1ou$ve seen system objects provided by the JavaScript runtime/ +i'e other object oriented languages&
customer or user defined objects can be created and used/ )o%ever& JavaScript objects differ from classic
IclassJ(based object oriented languages %hich have inheritance& encapsulation& and polymorphism constructs
built into the language/ JavaScript objects are dynamic and to support this dynamic behavior& a prototype(
based approach is ta'en to object creation/ The next sections should give you a good idea for ho% this
%or's/
There are t%o %ays to create objects %ith JavaScript: literally or %ith a constructor function/
LITERAL OBJECTS
+iteral JavaScript objects are defined using JavaScript Object Dotation ,JSOD./ Some may thin' that JSOD is
just a data format used for transmitting data from a server or remote system/ It is& but its real purpose is to
define JavaScript objects that have properties and executable methods& or actually functions/
"s an example& consider an object that models an account %ith an I-& name& and balance properties& %ith
methods that debit and credit the account/ igure 3 ,located on page 22. sho%s an account object model and
source code using JSOD for its Javascript implementation/
Page 28 of 34
5eyhole Soft%are& ++!/ 6788 State +ine 9oad& Suite :;; +ea%ood& 5S <<38< Tel 6==(;32(==<7 %%%/'eyholesoft%are/com
!opyright > 3824 5eyhole Soft%are& ++!/ "ll rights reserved/
Figure 2 Petty Cash account obect model and source code using JS!"
"dditionally& +isting 28 belo% sho%s a IliteralJ account object definition %ith debit and credit methods and
relevant properties:
Listing 1? Literal Acc!$nt O=>ect 'e#initi!n
ar account = { idJ 677;
na,eJ 'Ketty >ash';
balanceJ 7.77;
debitJ function(a,ount) { this.balance = this.balance 4 a,ount; return this; };
creditJ function(a,ount) { this.balance = this.balance 0 a,ount; return this; }
};
Dotice in the listing above that the account object has properties representing account I-& balance& and
name& along %ith methods defined for debiting and crediting/ *ethods are evaluated against the object
instance using the I/J operator/ Dotice ho% methods can be cascaded since the method implementations
return this. The expression belo% sho%s the cascading debit and credit calls to the account object:
account.credit(677.83).debit(37.L3);
console.lo&('Bccount na,e='0account.na,e0' 2alance = '0account.balance);
The dynamic nature of JavaScript can be seen %hen adding ne% properties or methods& as you simply add
them to the object/ )ere$s ho% a close() account method can be dynamically added to the account object:
account.close = function() { this.balance = 7;}; / Add new close function to account ob4ect
account.credit(677.83).debit(37.L3); / %ebit/credit account
console.lo&('Bccount na,e='0account.na,e0' 2alance = '0account.balance);
account.close(); / Close the account
"ll Objects are instances of the JavaScript system Object type& and is simply comprised of an associative
array and a prototype/ @e$ll tal' more about that later/ +isting 22 provides some insight into ho% properties
of an object are stored an associative array:
Listing 11 -r!perties st!re" as an ass!ciate" arra+
ar ob)ect = { %J 677; 8 Literal ob4ect
yJ 877;
addJ function() { console.lo&(this.% 0 this.y)}
}
for (!ey in ob)ect) {
console.lo&(!ey); 8 3utputs property names $ y add to the console
}
Property elements can be accessed using the property name/ +isting 23 ,located on page 23. sho%s a
literal object created as a mechanism to map state abbreviations to state name/
Page 22 of 34
5eyhole Soft%are& ++!/ 6788 State +ine 9oad& Suite :;; +ea%ood& 5S <<38< Tel 6==(;32(==<7 %%%/'eyholesoft%are/com
!opyright > 3824 5eyhole Soft%are& ++!/ "ll rights reserved/
var account # $ id% 1&&' ( Create an account obect )ith debit and credit methods
name% *Petty Cash*'
balance% &+&&'
debit% function,amount- $ this+balance # this+balance .
amount/ return this/ 0'
credit% function,amount- $ this+balance # this+balance 1
amount/ return this/ 0
0/
account+credit,1&&+22-+debit,2&+32-/ ( 4ebit and credit the account obect )ith cascading operator
console+log,*5ccount name#*1account+name1* 6alance # *1account+balance-
5ccount
balance % "umber
name % String
id % "umber
debit,amount-
credit,amount-
Listing 1& An e1a*ple !# $sing arra+ s$=script s+nta1
ar ,ap = { !sJ .Mansas.; 8 3b4ect 9ap of States
,oJ .Iissouri.;
caJ .>alifornia.
};
console.lo&(,ap:.!s.<); 8 Access by :ey, outputs ;ansas
Dotice ho% the object property is accessed using array type access& but instead of an index number the
name of the property is specified/
CONSTR%CTOR F%NCTION OBJECTS
"n alternative %ay to define and create an object is referred to as an object constructor/ This approach feels
a little more li'e the classic approach& as the classical Ine%J operator is used to create an instance/ "lso&
constructor objects allo% an instance to be initialiFed %ith supplied values/
In listing 24& the account object is defined and used %ith the constructor approach/ Dotice ho% the initial
balance is initialiFed and the instance is created %ith the ne% operator/
Listing 12 An e1a*ple !# !=>ect c!nstr$ct!r
ar Bccount = 8 Constructor account ob4ect
function(initial2alance) {
this.id = 877;
this.na,e = 'NOH';
this.balance = initial2alance
this.debit = function(a,ount) { this.balance =
this.balance 4 a,ount; return this; };
this.credit = function(a,ount) { this.balance = this.balance
0 a,ount; return this; }
};
ar ob)ect = new Bccount(3689.83); 8 Create instance
console.lo&('Bccount na,e = '0ob)ect.na,e0' 2alance = '0ob)ect.balance);
BEST -RACTICE. Lariables referencing constructor functions are typically camel(cased and %ith the first
character capitaliFed/ !reate a factory that hides the Sne%S 'ey%ord since it$s easy to forget/
unctions are discussed in an upcoming section/ But& as you have seen constructor objects loo' li'e
functions& loo' closely/ They really aren$t functionsT they provide a %ay to initialiFe objects& enclose the
structure of an object& and provide a %ay to IconstructJ objects %hen needed/ This is as opposed to defining
them literally/
-r!t!t+pes
Do% that %e have explored a couple of %ays to define and create objects& let$s dive under the covers and see
%hats going on %ith objects/
JavaScript is referred to as a Prototype(based language/ This can be contrasted to the classic class(based
languages in %hich classes contain methods and properties are defined/ "t runtime& class meta data is turned
into a type system object model/ )o%ever& available classes must be defined at construction time/
JavaScript$s dynamic nature applies a prototyped(based approach to objects/ "s indicated& JavaScript objects
are instances of an object %ith an associative array ,'eyCvalue. of other data objects or function objects/
"nd& as %e have seen& objects can be created at runtime& %ith methods and properties being added at %ill/
Every constructor(based object definition has a prototype property that points to the same prototype of
the constructor function/ "dding a ne% method to the constructor object is visible to all instances that have
been created from it& as sho%n in listing 2: located on page 24/
Page 23 of 34
5eyhole Soft%are& ++!/ 6788 State +ine 9oad& Suite :;; +ea%ood& 5S <<38< Tel 6==(;32(==<7 %%%/'eyholesoft%are/com
!opyright > 3824 5eyhole Soft%are& ++!/ "ll rights reserved/
Listing 14 A""ing a ne5 *et0!" t! t0e pr!t!t+pe
ar Ga,e = function() { 8 'ame constructor ob4ect definition
this.first = null;
this.,iddle = null;
this.last = null};

ar na,eB = new Ga,e(); 8 Instance is created
na,eB.first = '"ane';
na,eB.last = 'Hoe';

ar na,e2 = new Ga,e(); 8 Another instance is created
na,e2.first = '"ohn';
na,e2.last = 'Hoe';
Ga,e.prototype.,iddle = '>hris'J 8 9iddle name added to 'ame prototype

>onsole.lo&(na,eB.,iddle); 8 9iddle name is isible to both instances
>onsole.lo&(na,e2.,iddle);
+isting 2: sho%ed a definition of a constructor function object named Ga,e. It has t%o properties: first
and last name/ T%o instances are created using the new operator and properties are set/ Dotice these t%o
instances reference the constructor objects prototype property/ Then a middle name property is added to the
prototype reference/ This ma'es the middle(name property visible to both instances& na,eB and na,e2.
-ROTOT(-E CAININ,)INERITANCE
The previous section sho%ed ho% methods and properties that need to be shared across all instances can be
made global to all instances by adding properties to the constructor objects prototype/ @hen a property or
method is sent to an object during execution& the runtime environment %ill loo' for the propertyCmethod in
the current instance& then in the existing prototype and up the chain until Pb)ect.prototype is encountered/
This is sho%n in figure 4/
Figure 7 Prototype Chaining
8nheritance
This is referred to as prototype chaining and is ho% inheritance %or's in JavaScript/ The next expression
,located on page 2:. demonstrates this chaining behavior by adding a replicate() method to the built(in
Objects prototype property/
Page 24 of 34
5eyhole Soft%are& ++!/ 6788 State +ine 9oad& Suite :;; +ea%ood& 5S <<38< Tel 6==(;32(==<7 %%%/'eyholesoft%are/com
!opyright > 3824 5eyhole Soft%are& ++!/ "ll rights reserved/
Prototype
replicate,-
!bect
String
prototype
9y!bect
prototype
Prototype
Chain
Prototype
Chain
Prototype
replicate,- visible
to all obects
prototype
Pb)ect.prototype.repeat = function(count) { 8 All ob4ects now hae
return count < 6 Q '' J new Brray(count 0 6).)oin(this); replicate57 method
};
console.lo&(.'ello..repeat(9)); 8 logs <=ello=ello=ello<>
This ne% replicate() is no% visible to all objects/ @hile it %or's for String objects& it %ill probably thro%
an error trying to execute %hen run against other objects since the split() method is expecting a String
object/ So& adding the replicate() method to the String objects prototype ma'es it visible to only String
objects/
#trin&.prototype.repeat = function(count) { 8 All String ob4ects now hae
return count < 6 Q '' J new Brray(count 0 6).)oin(this); replicate57 method
};
console.lo&(.'ello..repeat(9)); 8 logs <=ello=ello=ello<>
"s you can see& this is similar to inheritance/ +et$s apply this to an anonymous function& sho%n %ith these
expressions in listing 2;:
Listing 16 -r!t!t+pe c0aining in0eritance 5it0 an an!n+*!$s #$ncti!n
ar RS = function() { this.% = 677;
this.y = 877 };

ar a = new RS(); / ?A >reate instance
a.,ultiply = function() { return this.% 1 this.y;}; / ?- Bdd ,ultiply ,ethod
console.lo&(a.,ultiply()); / lo&s 8777
ar b = new RS(); / ?C >reate another instance
console.lo&(b.,ultiply()); / ?% $rror ,ultiply() is not defined
RS.prototype.,ultiply = function() { return this.% 1 this.y;}; / ?& Bdd ,ultiply to RS prototype
console.lo&(b.,ultiply()); / ?" Iultiply is aailable and
displays 87777
The example defined an #1 constructor object ()& then assigned a multiply function (* and executes it/
Then another #1 instance is created (+ and the multiply method is issued& but it is undefined (D/ This is
because the ,ultiply() method %as added to an object& but not its prototype/ "dding the multiply function
the #1 constructor functions objects prototype (E& ma'es it available to all instances created from the #1
object ($/
-ROTOT(-ES IN ACTION IM-LEMENTIN, TE SIN,LETON -ATTERN
Prototype behavior can be seen in action %hen trying to implement the singleton pattern %ith JavaScript/
Singletons are a pattern seen commonly in classical object languages/ Its intent is to implement a global
single instance of an object/ @ith JavaScript it is easy& too easy& to ma'e an object a global variable in
JavaScript/ Simply set an object reference to the globally visible %indo% object/ )ere is ho% the current user
of an application can be made global:
>urrentEser = {user-dJ ')doe'; na,eJ'"ohn Hoe' };
or
window.>urrentEser = {user-dJ ')doe'; na,eJ'"ohn Hoe' };
or a large application& putting this global module definition in its o%n JavaScript file %ill help ma'e things
more modular and maintainable/ )o%ever& if this file is loaded or referenced multiple times& it %ill %ipe out
previous values/ So the single pattern can be applied to ensure only a single instance of an object exists no
matter ho% many times this file is loaded/ The singleton pattern for a global >urrentEser is sho%n in listing
2</
Page 2: of 34
5eyhole Soft%are& ++!/ 6788 State +ine 9oad& Suite :;; +ea%ood& 5S <<38< Tel 6==(;32(==<7 %%%/'eyholesoft%are/com
!opyright > 3824 5eyhole Soft%are& ++!/ "ll rights reserved/
Listing 18 Singlet!n instance i*ple*entati!n
ar >urrentEser = function() {
ar Eser = function() {
ar userid = '';
ar na,e = '';
return {
&etGa,e J function() {
return na,e;
};
&etEser-d J function() {
return userid;
};
setGa,e J function(newGa,e) {
na,e = newGa,e;
};
setEser-d J function(newEser-d) {
userid = newEser-d;
};
};
};
if (Eser.prototype.Tinstance) {
return Eser.prototype.Tinstance;
}
Eser.prototype.Tinstance = new Eser;
return Eser.prototype.Tinstance;
}();
8 set singleton alue
>urrentEser.setEser-d(.)doe.);
>urrentEser.setGa,e(."ohn Hoe.);
console.lo&(>urrentEser.&etEser-d());
JavaScript prototype behavior provides a convenient %ay to enforce the singleton instance of a current
user no matter ho% many times the file is loaded/ " closure is defined that returns the singleton instance/
The singleton instance is set to the constructor functions prototype for the first reGuest and subseGuent calls
just return the original instance/
"lso& notice ho% getterCsetter access methods %ere defined& as this is a practice not typically done in
JavaScript OO development/ But& for this example& it sho%s ho% access to the data can be encapsulated %ith
methods/
6. F%NCTIONS
Everything in JavaScript is an object& and functions are no exception/ JavaScript functions represent a
modular unit of execution and are considered first class objects& as they can be created literally& dynamically&
assigned to variables& and passed around as data/ +iteral functions are something you have already seen in
this tutorial/ )ere$s a basic literal function definition you$ve probably seen before:
function hello(orld() {
console.lo&(.hello world.);
}
8 e$ecute function
hello(orld();
+iteral functions are a'in to method implementations in classic languages li'e Java and !0/ JavaScript
being dynamic in nature does not really have much in common %ith compiled(based languages/ !omparisons
are probably made to Java due to the IJavaJ in IJavaScript/J
Page 2; of 34
5eyhole Soft%are& ++!/ 6788 State +ine 9oad& Suite :;; +ea%ood& 5S <<38< Tel 6==(;32(==<7 %%%/'eyholesoft%are/com
!opyright > 3824 5eyhole Soft%are& ++!/ "ll rights reserved/
One advantage that dynamic(based languages li'e JavaScript have over their compiler(based competitors
is that functional programming capabilities are made possible by the ability to treat chun's of code li'e data/
This can lead to elegant designs that do more %ith less code/
An!n+*!$s)Cl!s$res
"nonymous functions or closures are a po%erful element in JavaScript/ !losures are a 'ey element to
functional programming techniGues/ Other languages such as !0 provide closures/ Java has been promising
closures for a number of releases& but has yet to provide this capability/
!losure functions are defined and assigned to a variable that can be passed around just li'e a piece of
data& and then executed/ 1ou$ll see closures commonly used to provide callbac' and event handling
functionality/ unctions can be defined and assigned to a variable that can then be passed around and
executed/
!hec' out listing 2= belo%& as this example contrasts a literal function %ith one that is created
anonymously& or as a closure/
Listing 19 Literal #$ncti!n c!ntraste" 5it0 cl!s$re
function hello(orld() { 8 Literal function definition
console.lo&(.hello world.);
}
hello(orld(); 8 &$ecute function, outputs @hello worldA
ar hello = function() { console.lo&(.hello.); }; / %efine anonymous function and assign to ariable
hello(); / &$ecute function, outputs @helloA

ar lo& = function(te%t) { console.lo&(te%t); }; / %efine anonymous function with argument
lo&(.'ello (orld.); / &$ecute function, outputs @=ello WorldA
+et$s ma'e things a little more interesting %ith the next example/ These expressions define an anonymous
function that is passed into another function and then executed/ Dotice ho% arguments are handled in the
follo%ing expressions:
ar hello = function() { console.lo&(.hello.); }; / define hello function
ar e%ecutor = function(func) { console.lo&(func()); }; 8 define e$ecutor function
e%ecutor(hello); / ino:e e$ecutor function, pass in hello
function as an argument, outputs #hello#
Me*!i@ing
Since functions can be treated as data& an interesting feature becomes available& referred to as
ImemoiFation/J This feature provides the ability to hide or remember data/ Lariables scoped by an outer
function and referenced by an inner function remember their values every time the function is invo'ed/
*emoiFation can be seen in listing 26 ,located on page 2=./ This example implements a literal function
that returns anonymous functions for a specific operation/ Each operation function can then be executed and
results returned/ Dotice ho% the sum variable is remembered bet%een operation calls/
Page 2< of 34
5eyhole Soft%are& ++!/ 6788 State +ine 9oad& Suite :;; +ea%ood& 5S <<38< Tel 6==(;32(==<7 %%%/'eyholesoft%are/com
!opyright > 3824 5eyhole Soft%are& ++!/ "ll rights reserved/
Listing 1: Me*!i@ati!n Cl!s$re E1a*ple
function operation?actory(operation;initialUalue) { / ?* function that returns operation
closure function and sets initial alue
ar su, = initialUalue; / su, ariable will be *,e,oiFed by
operation closure functions
if (operation == .0.)
{ return function(%) { su, 0= %;return su,;} };
if (operation == .4.)
{ return function(%) { su, 4= %;return su,;} };
if (operation == .1.)
{ return function(%) { su, 1= %;return su,;} };
}
ar add = operation?actory(.0.;7); / ?2 &et operation functions fro, factory
ar subtract = operation?actory(.4.;877); and assi&n to ariable
ar ,ultiply = operation?actory(.1.;67.7);

add(677); / ?B e%ecute add function; su, ariable will be 677
console.lo&(add(877)); / ?) add 877; output will be 977; as the preious
add ariable is re,e,bered
subtract(677); / console output will be 37
console.lo&(subtract(37));
,ultiply(7.3); / console output will be 8.3
console.lo&(,ultiply(7.3));
+et$s %al' through code listing& as this is an important concept to see in action/ Step (1 defines an
operation?actory function that accepts an operation identifier and an initial value/ @hen called& a closure is
returned that performs an arithmetic operation against the outer functions su, variable/ Step (2 gets
operation closure functions from the factory and assigns them to variables/ Step (3 then invo'es the
function %ith a value of 288/ Step (4 invo'es the add function again %ith 388 and outputs 488 to the log/
Since the add function %as executed to separate times& you might thin' that the second add execution
%ould output 388/ !losure memoiFation remembers the sum variable across executions of the same function
instance/
@hat do you thin' the output of the expression sho%n belo% %ill beQ
ar add = operation?actory(.0.;677);
add(37);
add(37);
console.lo&(add(37));
If you guessed 3;8& then you are right/ The initial value of the ImemoiFedJ sum variable is set to 288/
E1ec$ti!n C!nte1t
This is a concept that causes confusion& especially %ith closures/ !lassical object oriented developers
understand the concept of the this 'ey%ord& %hich provides a %ay to reference an existing object reference/
This is especially useful %hen having to access propertiesCmethods and in passing object references around/
)o%ever& in JavaScript IthisJ may not be the IthisJ you %ere expecting/ Since JavaScript is dynamic code&
it has the concept of an execution stac'& and since JavaScript runs on a single thread& only one code bloc' is
visible in the execution context/ IthisJ is referencing that execution context/
)ere are some common JavaScript execution contexts for the this operator:
@indo%
-ocument
unction
*ethod
!onstructor *ethod
Page 2= of 34
5eyhole Soft%are& ++!/ 6788 State +ine 9oad& Suite :;; +ea%ood& 5S <<38< Tel 6==(;32(==<7 %%%/'eyholesoft%are/com
!opyright > 3824 5eyhole Soft%are& ++!/ "ll rights reserved/
)ere is %here context problems often occur/ Say you are defining a literal object method that defines a
closure that performs a calculation and prints results %hen a button is clic'ed/ It could loo' something li'e
the source belo%:
ar add = { / Literal ob4ect
su,J 7;
e%ecuteJ function(%;y) {this.su, = % 0 y; } / this is in ob4ect method conte$t
printJ function() {
ar btn = docu,ent.&et$le,ent2y-d(.printTbutton.); / Get document button ob4ect
btn.on>lic! = function() {
this.e%ecute(677;677)J / WILL "AIL, whyC!!!conte$t, or this will be in document conte$t
alert(this.su,); / WILL "AIL, whyC!!!conte$t or this will be in document conte$t
}
}
}
)o%ever& this %ill fail %hen the button is clic'ed %ith an error indicating that this.e%ecute() and
this.su, are undefined/ @hyQ Because %hen the closure function is executed& this %ill be in the )T*+
document context/
)o% can this be fixedQ *emoiFation is the ans%er/ The correct context is preserved and referenced in the
closure by defining a variable that references this/ This variable is then referenced by the closure&
preserving correct context reference& and not using the current context of this/
)ere is the same JavaScript snippet that %or's/ Dotice ho% the this context reference is memoiFed in the
closure:
ar add = { / Literal ob4ect
su,J 7;
e%ecuteJ function(%;y) {this.su, = % 0 y; } / this is in ob4ect method conte$t
printJ function() {

ar btn = docu,ent.&et$le,ent2y-d(.printTbutton.); / Get document button ob4ect
ar Tthis = this; / 0eference to this method conte$t

btn.on>lic! = function() {
Tthis.e%ecute(677;677)J / Won#t fail, memoiDed _this is correct conte$t
alert(Tthis.su,); / Won#t fail, memoiDed _this is correct conte$t
}
}
}
1ou can also supply an execution context/ It can also be specified and supplied to a function using the
function call or apply methods/
)ere$s an example:
function add(a;b) { / "unction definition
return this.% 0 this.y 0 a 0 b;
}
ar o = {%J677; yJ677}; / 3b4ect definition
console.lo&(add.call(o;877;877)); / Ino:e function with call, specifying a
conte$t for this! 3utputs (++ to console!
This is something that you %ill encounter often& especially in SP" development& %hen you %ill be %riting a
lot of JavaScript client logic to create user interface elements& and for reacting to events in the )T*+
document context/
F$ncti!n Cl!s$res in Acti!n an" M!"$larit+ S$pp!rt
*odularity and dependency injection are not mechanisms built into JavaScript/ @ith JavaScript& you can use
foldersCfiles to help modulariFe code/ !ompare this %ith other languagesT enforcing modularity in Java is
accomplished using pac'age definitions& %hile !0 uses Damespaces/ "s dependency injection is not a part of
Page 26 of 34
5eyhole Soft%are& ++!/ 6788 State +ine 9oad& Suite :;; +ea%ood& 5S <<38< Tel 6==(;32(==<7 %%%/'eyholesoft%are/com
!opyright > 3824 5eyhole Soft%are& ++!/ "ll rights reserved/
any language& frame%or's have filled the gap/ This is changing as both !0 and Java have indicated a future
in implementing built(in dependency injection mechanisms in their language specifications/
*odularity and dependency injection are 'ey for managing SP" li'e applications that have rich user
interaction reGuirements/ )o%ever& the goal of this section is to understand JavaScript functions and
closures/ ?nderstanding ho% to apply modularity %ill help %ith this goal/ igure : illustrates the concept of
modularity and dependency injection& sho%ing ho% modules can be used and dependent modules injected:
Figure : 9odularity and 4ependency 8nection
"vailable JavaScript modularity mechanisms are functions or JavaScript code defined in separate files that
are loaded using a <script> tag/ *odularity allo%s complexity and information to be hidden from consumers
of a module/ !lassical OO languages provide language access visibility to methods and properties of objects/
"ccess modifiers are available and can be specified to ma'e properties and methods private/ Private access
modifiers prevents developers from changing or accessing elements that are not a part of a module$s public
access "PI/ JavaScript does have an access modifier& ho%ever a pattern has been invented that allo%s
methods and attributes to be hidden/
The module pattern evaluates a function closure that returns a literal object function methods that
accesses the private data/ +isting 27 sho%s ho% an address object is modulariFed:
Listing 1; M!"$le -attern #!r a""ress
ar addressIodule = (function () { / Address 9odule reference to ob4ect literal
ar address = :'street';'city';'state';'Fip';<; / Array holds address segments 5street, city;
return { state, Dip, etc!7
streetJ function (street) {
address:7< = street;
return this;
};
cityJ function(city) {
address:6< = city;
return this;
};
stateJ function(state) {
address:8< = state;
return this;
};
FipJ function(Fip) {
address:9< = Fip;
return this;
};
for,atJ function () {
return address:7<0.Vn.0address:6<0';'0address:8<0' '0address:9<;
}
};
})(); 8 "unction closure ealuated on load
addressIodule.street('689 $asy #treet').city('@awrence').state('M#').Fip('68953W'); 8 Ino:es module
methods
console.lo&(addressIodule.for,at()); / 3utputs formatted address to console
Page 27 of 34
5eyhole Soft%are& ++!/ 6788 State +ine 9oad& Suite :;; +ea%ood& 5S <<38< Tel 6==(;32(==<7 %%%/'eyholesoft%are/com
!opyright > 3824 5eyhole Soft%are& ++!/ "ll rights reserved/
application+s
address+s formatter+s
;uery+s
customer+s
uses
uses
uses
inects
inects
inects
inects
Dotice ho% in listing 27& the address elements are stored in an array/ *ethods are defined to allo% array
elements to be set& and a method to return a formatted address is defined/ Only the methods returned by
the literal object returned are visible to the user of the address object/ This pattern effectively ma'es the
address array visible or private to the returned literal object/
'epen"enc+ In>ecti!n
"nother pattern commonly found in classical languages is dependency injection/ This is simply a pattern for
referencing other IdependentJ modules/ -oing this in a consistent manner communicates dependent modules
and provides a %ay to report or assert modules that are not present& %hich can help %ith maintenance and
debugging/ +isting 38 sho%s ho% the previous module pattern introduces a module that formats addresses:
Listing &? In>ecting a "epen"ent a""ress *!"$le
ar addressIodule = (function (printer) { / /rinter module supplied to address module
ar address = :'street';'city';'state';'Fip';<;
return {
streetJ function (street) {
address:7< = street;
return this;
};
cityJ function(city) {
address:6< = city;
return this;
};
stateJ function(state) {
address:8< = state;
return this;
};
FipJ function(Fip) {
address:9< = Fip;
return this;
};
for,atJ function () {
return printer.for,at(address); / &ngage printer module and format address
}
};
})(printerIodule); / printer module reference, assume this is a
global ariable
addressIodule.street('689 $asy #treet').city('@awrence').state('M#').Fip('68953W');
/ chec: the counter alue and reset, 3utputsE *
console.lo&(addressIodule.for,at());
The address module is IinjectedJ as an argument in module closure& and a reference to the injected
module,s. are applied in the module loaded function call/
8. EACE-TIONS ) ERRORS
@hen errors occur during JavaScript execution& an error object is thro%n/ 1ou may be surprised to 'no% that
problems can be caught by errors being thro%n or raised/ Exceptions are an integral part of Java& !0& and
!MM languages/ 1ou don$t see a lot of exception handling code in JavaScript/ Typed languages mentioned
above have the advantage of having exception types that can provide additional debugging information as to
%hy the exception occurred/
Exceptions in JavaScript are actually errors that have occurred during execution/ +et$s say you %ant to
catch an undefined error& here$s ho% this is accomplished %ith a try/catc, code bloc':
try {
ar % = 7;
ar F = % 0 y;
} catch (error) { / F not being defined will throw an e$ception
console.lo&(.S is not defined; you bi& du,,y J).); / catch bloc: outputs message to console
}
Page 38 of 34
5eyhole Soft%are& ++!/ 6788 State +ine 9oad& Suite :;; +ea%ood& 5S <<38< Tel 6==(;32(==<7 %%%/'eyholesoft%are/com
!opyright > 3824 5eyhole Soft%are& ++!/ "ll rights reserved/
1ou can also thro% or raise errors in your code using the throw clause/ 1ou can thro% any object type
and this instance %ill be available in the catch bloc'/ )ere are some examples of thro%ing an error %ith
various object types:
=hrow 46; / throw 6* number
throw '$rror Iessa&e'; / throw error message string
throw {codeJ 677; ,essa&eJ 'error ,essa&e' ); / throw ob4ect literal instance with error
information
!atch bloc's %ill have access to the object instances that are thro%n/
AJAA
"synchronous JavaScript and #*+ ,"J"#. is a technology supported by all bro%sers and is a simple
mechanism that provides a profoundly improved user experience/ Before "J"#& bro%sers and JavaScript code
%ould be executed %henever an )T*+ page %as reGuested from the %eb server/ Then the bro%ser& along
%ith JavaScript& %ould render an )T*+ user interface/
"J"# provides a %ay to reGuest #*+ or String data from the %eb server and then process this data %ith
JavaScript/ Being able to update individual )T*+ elements at any granularity li'ely started the movement
to%ards the SP" applications %e see today/ 1ou are probably already using "J"# if you are developing %eb
applications using JEE or /DET server side *L! frame%or's/ *any ?I components leverage "J"# to provide a
more responsive user interface/
+et$s dive into ho% an "J"# reGuest is made from JavaScript and a response is processed/ 1ou$ve probably
noticed the #*+ emphasis %ith "J"#/ This is due to expecting an "J"# server reGuest to return an )T*+
document object model ,-O*.& %hich is in #*+ format/ +isting 32 sho%s JavaScript that ma'es an "J"# call
to return an )T*+C#*+ document from the %eb server:
Listing &1 AML AJAA reB$est
ar %,lhttp = new RI@'ttpNeXuest(); 8 Create re,uest instance
%,lhttp.onreadystatechan&e=function() 8 /rocess serer side results from call
{
if (%,lhttp.ready#tate==5 OO %,lhttp.status==877)
{
docu,ent.&et$le,ent2y-d(.,yHi.).inner'=I@=%,lhttp.responseRI@; 8 G9L response
}
}
%,lhttp.open(.Y$=.;.info.ht,l.;true); 8 Serer side resource to access
%,lhttp.send(); 8 Initiate A.AG 0e,uest
The %,lhttp is a global object provided by the JavaScript runtime/ The open method specifies put& post&
or get operation& the file to open& and returns from the server true if this an asynchronous call& %hich ma'es
it "J"#/ Other%ise it$s a synchronous call/ " callbac' function assigned to the onreadystatechan&e property
%ill process the results/
"J"# reGuests can also return string values from the server instead of #*+/ Since a JSOD string is easily
turned into actual JSOD %ith JavaScript& SP" applications %ill typically utiliFe server ?9+ reGuests that return
JSOD strings containing only application data/ SP" applications produce )T*+ on the client side %ith
JavaScript& so JSOD data %ill be merged %ith client side dynamic )T*+/
+isting 33 ,located on page 33. sho%s ho% JavaScript invo'es a server side ?9+ that returns a JSOD
string and then turns the string into a JSOD object/
Page 32 of 34
5eyhole Soft%are& ++!/ 6788 State +ine 9oad& Suite :;; +ea%ood& 5S <<38< Tel 6==(;32(==<7 %%%/'eyholesoft%are/com
!opyright > 3824 5eyhole Soft%are& ++!/ "ll rights reserved/
Listing && JSON AJAA ReB$est
ar %,lhttp = new RI@'ttpNeXuest(); 8 Create re,uest instance
%,lhttp.onreadystatechan&e=function() 8 /rocess serer side results from call
{
if (%,lhttp.ready#tate==5 OO %,lhttp.status==877)
{
ar )son = "#PG.parse(%,lhttp.response=e%t); 8 /arse .S3' He$t to .S3'
}
}
%,lhttp.open(.Y$=.;.info.do.;true); 8 Serer side resource to access
%,lhttp.send(); / -nitiate B"BR NeXuest
The mechanism of "J"# is supported by all modern bro%sers and is essential to SP"(based applications/
?pcoming tutorials %ill introduce SP" JavaScript frame%or's/ One mechanism some of these frame%or's
implement is a %ay to access server side data in a 9ESTful manner/ "J"# allo%s these frame%or's to access
server side data then update a portion of the user interface& %ith no page refresh& reinforcing a 9ich ?ser
Interface/
9. S%MMAR(
This tutorial introduced beginning and advanced JavaScript programming features and concepts/ " thorough
understanding of these topics is necessary for building %eb SP" applications& as much JavaScript %ill be
developed& used& and applied throughout that process/
If some concepts are still fuFFy& I recommend that you play around %ith and modify some of the samples
to see if it helps your understanding/
Re#erences
Osmani& "ddy/ Learning !a"aScript #esign Patterns. Lolume 2/;/3
http%<<addyosmani+com<resources<essentialsdesignpatterns<boo=<
9o>illa 4eveloper "et)or=+ https%<<developer+mo>illa+org<en.?S<
@7 Schools+ http%<<)))+)7schools+com<
CommonJS @i=i Community+ http%<<)i=i+commons+org<)i=i<CommonJS
5synchronous 9odule 4efinition ,n+d+- 8n Wikipedia+
http%<<en+)i=ipedia+org<)i=i<5synchronousAmoduleAdefinition
A=!$t T0e A$t0!r
-avid Pitt is a Sr/ Solutions "rchitect and *anaging Partner of 5eyhole Soft%are %ith nearly 3; years IT
experience/ Since 2777& he has been leading and mentoring development teams %ith soft%are development
utiliFing Java ,JEE. and /DET ,!0. based technologies/ *ost recently& -avid has been helping organiFations to
ma'e the architecture shift to JavaScriptC)T*+; and use best practices to create rich client and single page
applications/
A=!$t Ce+0!le S!#t5are
5eyhole Soft%are is a *id%est(based soft%are development and consulting firm %ith specialiFation in Java&
JavaScript and /DET technologies/ Experts in application development& technical mentoring& and the
integration of enterprise(level solutions& 5eyhole %as founded on the principle of delivering Guality solutions
through a talented technical team/
Page 33 of 34
5eyhole Soft%are& ++!/ 6788 State +ine 9oad& Suite :;; +ea%ood& 5S <<38< Tel 6==(;32(==<7 %%%/'eyholesoft%are/com
!opyright > 3824 5eyhole Soft%are& ++!/ "ll rights reserved/
Ce+0!le S!#t5are JavaScript Services
Outsourced Development K " 5eyhole team provided to perform analysis& design& development&
testing and deployment of JavaScript(based SP" applications
Development Support K SpecialiFed members of our team participate as project team member and
perform development activities
-TM.# / /avascript Education K 3(day custom course to teach your team the ins and outs of
effective enterprise development %ith JavaScript
Mentorin0 / 1layer +oac,in0 K !oaching and 'no%ledge transfer& %or'ing %ith your team to help
them understand& use and 'no% best practices in JavaScript and SP" development
F!r M!re In#!r*ati!n
Keyhole Corporate Kansas City
6788 State +ine 9oad& Suite :;;
+ea%ood& 5S <<38<
Tel: ,6==. ;32(==<7
Keyhole St. Louis
Phone: ,42:. 437(2<77
Keyhole Chicago
388 E 9andolph St
!hicago& I+ <8<82
Phone: ,<48. :<8(642=
T%TORIAL -%BLISE'. OCTOBER 1:D &?12
Page 34 of 34
5eyhole Soft%are& ++!/ 6788 State +ine 9oad& Suite :;; +ea%ood& 5S <<38< Tel 6==(;32(==<7 %%%/'eyholesoft%are/com
!opyright > 3824 5eyhole Soft%are& ++!/ "ll rights reserved/

You might also like