Vous êtes sur la page 1sur 29

Intake SS - 0S }ulie Iskanuei

2u12-2u1S

1
Client-Siue }avaSciipt
Lectuie 1

"#$%&'()$*&# $& +,-,.)%*/$

It is a
Lightweight sciipting language
Inteipieteu at iuntime by }avaSciipt engines

It is a
i

Bynamic sciipting language,
Bas flexible uata-type
Functions aie objects.

ii
Fiom Bienuan Eich, }avaSciipt Cieatoi, Inteiview
"Naking web pages come alive "

Netscape neeueu a sciipting language oi some kinu of language insiue the
biowsei that coulu be useu to automate paits of a web page oi make a web page
moie uynamic. The new language shoulu look like }ava, but be a sciipting
language.

LiveSciipt was the official name it was given when it fiist shippeu in beta ieleases
of Netscape Navigatoi 2.u in Septembei 199S, but was ienameu to }avaSciipt in a
joint announcement with Sun on Becembei 4, 199S.

Biffeience between }ava anu }avaSciipt can be summaiizeu to:

+,-, +,-,.)%*/$
Stiongly-typeu Loosely-typeu
Static Bynamic
Classical Piototypal
Classes Functions
Constiuctois Functions
Nethous Functions



Intake SS - 0S }ulie Iskanuei
2u12-2u1S

2
i
Stanuaiuizing }avaSciipt staiteu iight aftei Navigatoi S.u was ieleaseu, in
August 1996. A uiaft stanuaiu baseu on }avaSciipt was submitteu to
the Euiopean Computei Nanufactuieis' Association (ECNA), the inteinational
communications stanuaius bouy, baseu in ueneva, Switzeilanu. ECNA auopteu it
in }une 1997, anu it has also just been appioveu as an IS0stanuaiu. The stanuaiu
is now officially calleu ECNASciipt. The BTNL pait, the Bocument 0bject Nouel
(B0N), is stanuaiuizeu by the WSC.

BTNL is ieau anu piocesseu by the web biowsei. When the biowsei ieaus
}avaSciipt coue within youi BTNL uocument, it piocesses the coue, then uisplays
any output within the web page. The computei ieauing the }avaSciipt must have
a }avaSciipt inteipietei, a piogiam that inteipiets the sciipt anu iuns it, anu that
inteipietei must be enableu.
If theie aie any eiiois in the coue wiitten in a compileu language, those eiiois
will pop up when the coue is compileu. In the case of an inteipieteu language,
eiiois won't become appaient until the inteipietei executes the coue.
}avaSciipt, being a sciipting language, allows youi web page to 'think'. It allows
uevelopeis to auu incieaseu inteiaction, infoimation piocessing, anu contiol in
web-baseu content.
01,$ ,%2 $12 $&&34 #22'2'5
All that is neeu is:
1. A plain text euitoi,
2. A web biowsei.
012%2 $& 2672' +,-,.)%*/$5
"#4*'2 89:;
You can place the }avaSciipt between <sciipt> tags insiue the BTNL uocument. It
can be auueu in the <heau> section especially function uefinitions. It can also be
auueu insiue the bouy.
<!B0CTYPF btml~
<btml~
<beoJ~
<script type="text,jovoscript"~
}ovoScript qoes bere...
<,script~
<,beoJ~
Intake SS - 0S }ulie Iskanuei
2u12-2u1S

S
<boJy~
Hork-up qoes bere...
<,boJy~
<,btml~
"# <=$2%#,3 >*32
A bettei technique is to place youi }avaSciipt coue into a sepaiate file. The file is
saveu with extension .js. It will contain only }avaSciipt coue. The BTNL file will
only link to that file, using the sic attiibute in <sciipt> tag.
<!B0CTYPF btml~
<btml~
<beoJ~
<script type="text,jovoscript" src="file.js"~
<,script~
<,beoJ~
<boJy~
Hork-up qoes bere...
<,boJy~
<,btml~
any sciipt wiitten insiue the <sciipt> tag now, will be ignoieu.
iii
+?@?.AB"C9 .DE9?F
.$,$262#$4

Statements in }avaSciipt aie the builuing blocks of any sciipt. }avaSciipt is ),42G
42#4*$*-2H
Statements aie sepaiateu, by placing them on uiffeient lines.
first stotement
seconJ stotement
If a numbei of statements aie on the same line, you must sepaiate them with
semicolons.
first stotement; seconJ stotement;
It is goou piogiamming piactice to place a semicolon at the enu of eveiy
statement.
first stotement;
seconJ stotement;

A&662#$4

Comments aie statements that aie ignoieu by the }avaSciipt inteipietei.
Comments aie useu to uocument anu note youi coue. Theie aie two types of
Intake SS - 0S }ulie Iskanuei
2u12-2u1S

4
comments. The fiist is single-line comments ''
,, Note to self: comments ore qooJ.
The othei type is when you want to comment out multiple lines '*....*'
,* Note to self:
comments ore qooJ *,

*-
@,%*,7324

vaiiables aie useu to stoie uata.
Bata stoieu in a vaiiable can be changeu multiple times.
To use a vaiiable, you must:
1. Beclaie a vaiiable.
2. Initialize it.

To ueclaie a vaiiable use vor , you uon't neeu to set the uata type.

<=,6/32I
vor o;
vor o2;
vor floq;

Initializing can be uone in the same step of ueclaiing the vaiiable oi on a sepaiate
step aftei ueclaiing it. Seveial vaiiables can be ueclaieu in one statement
sepaiateu by commas.

<=,6/32I
vor o=2;
vor o2;
o2="Eello All!!";
vor floq=true;
vor b=4, nome="Smitb", f;

EHJH ln }ovoScript, if you ossiqn o volue to o vorioble tbot bosnt yet been JecloreJ,
tbe vorioble is JecloreJ outomoticolly. Altbouqb Jeclorinq voriobles beforebonJ
isnt requireJ in }ovoScript, its still qooJ proqromminq proctice.

vaiiable names can contain only letteis, numbeis, uollai symbols, anu
unueiscoies.
K*,3&L(24 ,#' ?32%$4
Theie aie thiee types of uialogue boxes suppoiteu in all majoi biowseis: aleit() ,
confiim() , anu piompt(). All of these aie membeis of the winuow object, but, like
Intake SS - 0S }ulie Iskanuei
2u12-2u1S

S
all membeis of winuow, can just be accesseu by name uiiectly, oi with the
winuow piefix.
,32%$MN
aleit() is a veiy basic moual notice box with a message insiue it. By moJol I mean
what the usei cannot inteiact with the biowsei oi pioceeu in any way until
acknowleuge the message by clicking 0k.
olert{Eello All);
gives:

This box will look uiffeient uepenuing on the usei ' s opeiating system anu
biowsei, anu you cannot customize its look anu feel.
)&#>*%6MN
confiim() gives the usei a simple binaiy choice, 0K oi Cancel. The ietuin of the
statement is tiue oi false. Tiue if 0k was piesseu, anu false if Cancel was piesseu.
vor result=confirm{Are you sure?);
Execution of the expiession will tempoiaiily suspenu until the usei closes the
uialogue.



Intake SS - 0S }ulie Iskanuei
2u12-2u1S

6
/%&6/$MN
piompt() allow useis to input some text that will be sent to the }avaSciipt coue.
The piompt() methou takes two aiguments:
prompt{uestion, Befoultvolue)
The Question is the message text that will be shown above the text box.
The Befaultvalue aigument will be the staiting text insiue the text box. If you
uon't want ony text in the text box, leave this as an empty stiing (uon't leave it
out, though).
If 0K is piesseu, the uialogue will ietuin a stiing containing the text typeu by the
usei. If Cancel is piesseu, it will ietuin null
prompt{Wbot is your nome?, Type your nome);

-*
K,$, 9O/24

C%*6*$*-2 K,$, 9O/24I

Any value that you use is of a ceitain type. In }avaSciipt, theie aie the following
primitive uata types:

1. Numbei: incluues floating point anu integeis,
foi example 1, 1uu, S.14.
2. Stiing: any numbei of chaiacteis,
foi example "a", "one", "one 2 thiee".
S. Boolean: can be eithei tiue oi false.
4. 0nuefineu: when accessing a vaiiable that uoesn't exist (not yet ueclaieu)
oi a ueclaieu vaiiable but not initializeu.
S. Null: special uata type that can only one value, the null value. It means no
value, an empty value, nothing.

Stiings must be encloseu in single quotes oi uouble quotes.
Intake SS - 0S }ulie Iskanuei
2u12-2u1S

7
vor mooJ = 'boppy';
vor mooJ = "boppy";

If youi stiing contains the uouble-quote chaiactei, then it use single quotes to
enclose the stiing anu vice-veisa oi use escaping with '\'.
vor mooJ = "Jon't osk";

EHJH Whethei you ueciue to use uouble oi single quotes, it's best to be )&#4*4$2#$.
Changing youi usage makes youi coue less ieauable.

The uiffeience between null anu unuefineu is that if a vaiiable has a value null, it
is uefineu but has a value that is nothing.

Any value that uoesn't belong to one of the five piimitive types listeu above is an
object. Even null is consiueieu an object, having an object (something) that is
actually nothing.

Piogiamming languages that iequiie explicit typing aie calleu stiongly typeu
languages. Because typing is not iequiieu in }avaSciipt, it is a un-typeu language.
This means that you can change the uata type of a vaiiable at any stage.

<=,6/32I
vor oqe = "tbirty tbree";
oqe = SS;

"#>*#*$O
It iepiesents a numbei too big foi }avaSciipt to hanule. Infinity is inueeu a
numbei. The biggest numbei }avaSciipt can hanule is
1.79769S1S4862S1S7e+Su8 while the smallest is Se-S24.

E,E
It is "Not A Numbei",
You get E,E when you tiy to peifoim an opeiation that assumes numbeis but
the opeiation fails. Foi example, if you tiy to multiply 1u by the chaiactei "f", the
iesult is E,E.

P/2%,$&%4

?%*$162$*) P/2%,$&%4
Intake SS - 0S }ulie Iskanuei
2u12-2u1S

8


;&L*),3 P/2%,$&%4

They woik with boolean values.
Intake SS - 0S }ulie Iskanuei
2u12-2u1S

9
1. ! logical N0T (negation)
2. && logical ANB
S. || logical 0R


A&6/,%*4&# P/2%,$&%4

Intake SS - 0S }ulie Iskanuei
2u12-2u1S

1u
Q42>(3 J(*3$G*# R(#)$*&#4

Intake SS - 0S }ulie Iskanuei
2u12-2u1S

11

+,-,.)%*/$ P7S2)$4
K,$2 P7S2)$
It is useu foi manipulating uate anu time. The Bote object pioviues a numbei of
methous foi getting oi setting specific infoimation about the uate anu time. The
uate is baseu on the 0NIX uate staiting at }anuaiy 1, 197u (in uieenwich Nean
TimeS |uNTj), anu uoesn't suppoit uates befoie that time.
Because client-siue }avaSciipt piogiams iun on a biowsei, the Bote object
ietuins times anu uates that aie local to the biowsei, not the seivei.
We declare a variable with Date object use Date constructor function. If no arguments
are passed to the Date object constructor, it returns the local date and time
Example:
var d=new Date() // Date {Sun Dec 30 2012 17:16:21 GMT+0200 (EET)}
There are five formats that can be passed as arguments when creating a Date object;
new Bote{"Hontb JJ, yyyy bb:mm:ss")
Intake SS - 0S }ulie Iskanuei
2u12-2u1S

12
new Bote{"Hontb JJ, yyyy")
new Bote{yy,mm,JJ,bb,mm,ss)
new Bote{yy,mm,JJ)
new Bote{milliseconJs)
Example:
myJote = new Bote{)
myJote = new Bote{"Horcb 1S, 2010 09:2S:00")
myJote = new Bote{"Horcb 1S, 2010")
myJote = new Bote{10,2,1S)
myJote = new Bote{10,2,1S,9,2S,0)
myJote = new Bote{S00);

Intake SS - 0S }ulie Iskanuei
2u12-2u1S

1S


Intake SS - 0S }ulie Iskanuei
2u12-2u1S

14

:,$1 P7S2)$
Nath is a little uiffeient fiom the othei built-in global objects.
It's not a noimal constiuctoi function anu theiefoie cannot be useu with 'new' to
cieate objects. Nath is a built-in global object, which pioviues a numbei of
methous anu piopeities that aie useful foi mathematical opeiations, but can't be
instantiateu.
Nath's piopeities aie constants so you can't change theii values. Theii names aie
all in uppei case to emphasize the uiffeience between them anu a noimal
vaiiable piopeity.

Intake SS - 0S }ulie Iskanuei
2u12-2u1S

1S
:,$1 C%&/2%$*24


:,$1 :2$1&'4I
Intake SS - 0S }ulie Iskanuei
2u12-2u1S

16


v
?%%,O4
An aiiay is a giouping of multiple values unuei the same name. Each one of these
values is an element of the aiiay.
An aiiay can be ueclaieu in one of the following ways:
vor myorr=[]; ,,Jeclorinq on orroy literol
vor myorr=[1 , 2 , tbree,four,folse];
vor myorr= new Arroy{) ,,usinq orroy constructor.
Intake SS - 0S }ulie Iskanuei
2u12-2u1S

17
vor myorr=new Arroy{2) ,,on orroy witb 2 unJefineJ elements
vor myorr=new Arroy{1,2,r,true); ,,on orroy witb 4 elements
Specifying the numbei of elements is optional. You can ueclaie an aiiay
withwithout a numbei of elements:
Auuing elements to an aiiay is calleu populating. When you populate an aiiay,
you specify not just the value of the element anu the inuex of the element, i.e the
numbei of the element staiting fiom u.
orroy[inJex] = element;

<=,6/32I
vor myorr=[]
myorr[0]=1;
myorr[S]=Eello;
myorr[6]=folse;
This example makes oui aiiay of 7 elements, only S has values while the iest aie
unuefineu.
[1, undefined, undefined, "Hello", undefined, undefined, false]
To ietiieve an element fiom the aiiay you use the inuex.
<=,6/32I
vor x=myorr[0]; ,,x will be 1
vor y=myorr[S]; ,,y will be Eello
To uelete an element of the aiiay
Jelete orroy[inJex]
<=,6/32I
Jelete myorr[S]
[1, undefined, undefined, undefined, undefined, false]
The element in one aiiay can be anothei aiiay (Aiiay of aiiays).
<=,6/32I
vor o = [1, "two", folse, null, unJefineJ]; ,, [1, "two", folse, null, unJefineJ]
o[S] = [1,2,S]; ,,onotber orroy [1, 2, S]
,,o= [1, "two", folse, null, unJefineJ, [1, 2, S]]

To create a 2D array
Intake SS - 0S }ulie Iskanuei
2u12-2u1S

18

var a = [[1,2,3],[4,5,6]];
// ar[0]= [1, 2, 3]
//ar[2]=[4,5,6]

To access an element in the nested array, you refer to the element index in another set
of square brackets.
a[0][0]=1
ar[1][2]=6
To access individual characters inside a string, use array notation.
var s = 'one';
// s[0]="o"
//s[1] ="n"
//s[2] ="e"

Arrays can be views as a key/value pair. For example myarr array can be viewed as:
Key Value
0 1
1 undefined
2 undefined
3 Hello
4 undefined
5 undefined
6 false
which leads us to associative arrays.
?44&)*,$*-2 ,%%,O4 M8,41N
The inuex of elements can be a stiing insteau of numbeis:
<=,6/32I
vor stuJents = Arroy{);
stuJents["AbmeJ"] = 22;
stuJents["HobomeJ"] = SS;
stuJents["lbrobim"] = 44;
Key Value
Ahmed 22
Mohamed 33
Ibrahim 44
This is the way }avaSciipt cieate anu stoie objects as will be shown in the 0bjects
section.
Intake SS - 0S }ulie Iskanuei
2u12-2u1S

19
To iefei to elements use keys insteau of inuex.
vor x= stuJents["AbmeJ"]
<=,6/32I
var students = Array();
var std=[];
std[name]=Ahmed
std[age]=20;
std[total]=200;
students[0]= std;
var std=[];
std[name]=John
std[age]=22;
std[total]=220;
students[1]= std;
var std=[];
std[name]=Mona
std[age]=20;
std[total]=230;
students[2]= std;
Now to get name of seconu stuuents, stuuents|2j|'name'j. It can be accesseu also
by uot notation, stuuents|2j.name
EHJH 0se squaie biackets when keys contain spaces oi aie ieseiveu woius.
?%%,O C%&/2%$*24
length: ietuins the numbei of elements in the aiiay.
?%%,O :2$1&'4
Intake SS - 0S }ulie Iskanuei
2u12-2u1S

2u

v
A&#$%&3 .$,$262#$4
A&#'*$*&#,34
Conuitional statements aie useu when uecisions neeu to be maue anu bianching
of coue occuis.
TH *>UU2342
if {conJition)
{
stotements;
]
The conuition is containeu within paientheses. The conuition always iesolves to
a Boolean value (tiuefalse).
The statement oi statements containeu within the cuily biaces will be executeu *>
,#' &#3O *> the iesult of the conuition is tiue.
<=,6/32I
Intake SS - 0S }ulie Iskanuei
2u12-2u1S

21
vai x=piompt("Entei a numbei less than 1uu",u);
x=paiseInt(x);
if(isNaN(x) || x>1uu)
{
aleit('Wiong Answei')
}
The aleit will only be shown if x is not a numbei (i.e. usei enteieu letteis insteau
of numbeis), oi x is gieatei than 1uu.
The if statement can be extenueu using else.
if {conJition)
{
stotements;
]
else
{
stotements
]

<=,6/32I
vai x=piompt("Entei a numbei less than 1uu",u);
x=paiseInt(x);
if(isNaN(x) || x>1uu)
{
aleit('Wiong Answei')
}
else
{
aleit('Coiiect Answei');
}
Now if the conuition is false the othei aleit appeais. Nesteu if...else is also
suppoiteu.
<=,6/32I
vor x=prompt{"Fnter o number less tbon 100",0);
x=porselnt{x);
if{isNoN{x))
{
olert{'Wronq Answer.nPleose enter o voliJ number')
]
else
{
if{x~100)
olert{'Wronq onswer.n Pleose enter o number < 100');
Intake SS - 0S }ulie Iskanuei
2u12-2u1S

22
else
olert{'Correct Answer')
]

2. .V*$)1
Replaces if when checking foi multiple equalities.

switcb {expression) {
cose expression1:
stotements
breok;
cose expression2:
stotements
breok;
Jefoult:
stotements
breok;
]

The expiession most often contains a vaiiable, but can be anything that ietuins a
value.
Each case statement is followeu by an expiession. The iesult of the case
expiession is compaieu to the expiession placeu aftei the switch statement. If the
iesult of the compaiison is tiue, the coue that follows the colon aftei the case is
executeu.

Theie is an optional bieak statement to signal the enu of the case block. If this
bieak statement is ieacheu, the switch teiminates.

0theiwise, if the bieak is missing, we entei the next case block, which shoulu be
avoiueu. This is calleu 'fall-thiough'. Thus, K&#W$ >&%L2$ $& 7%2,XH

Theie's an optional uefault statement, which is followeu by a block of coue that is
executeu if none of the pievious cases evaluateu to tiue.

<=,6/32I
vor o = '1';
vor result = '';
switcb {o) {
cose 1:
result = 'Number 1';
breok;
cose '1':
result = 'Strinq 1';
breok;
Jefoult:
Intake SS - 0S }ulie Iskanuei
2u12-2u1S

2S
result = 'l Jon't know';
breok;
]

When executing the coue, iesult=Y.$%*#L TY.
;&&/4
To execute the same block of coue a numbei of times, you'll neeu to use a looping
statement. The block of coue within a looping statement continues to be executeu
as long as the a specifieu conuition is tiue. When the conuition is no longei tiue,
the loop stops.
TH V1*32
wbile {conJition)
{
stotements;
]

<=,6/32I
vor count = 1;
wbile {count < 11)
{
olert {count);
count--;
]
This coue will aleit the numbeis fiom 1 to1u.
ZH '&HHHV1*32
It is similai to the while loop, except that the conuition is testeu aftei executing
the coue. If the conuition is false fiom the stait, the coue is executeu once. If we
useu while, the coue will nevei be executeu.
Jo
{
stotements;
] wbile {conJition);

<=,6/32I
vor count = 1;
uo
Intake SS - 0S }ulie Iskanuei
2u12-2u1S

24
{
count++;
aleit (count);
} while (count < 11);
The aleit message appeais ten times. Aftei the loop is finisheu, the value of the
vaiiable count is eleven.
Now consiuei this vaiiation:
vor count = 1;
Jo
{
olert {count);
count--;
] wbile {count < 1);
In this case, the conuition nevei evaluates as tiue. The value of count is one to
begin with so it is nevei less than one. Yet the uo loop is still executeu once. You
will still see one aleit message.
[H >&%
The foi loop useu foi executing some coue a specific numbei of times.
for {initiol conJition; test conJition; olter conJition)
{
stotements;
]

<=,6/32I
for {vor count = 1; count < 11; count-- )
{
olert {count);
]
The coue will be executeu exactly ten times.
0ne of the most common uses of the 'for' loop is to act on eveiy element of an
aiiay.
vor beotles = Arroy{"}obn","Poul","6eorqe","Rinqo");
for {vor count = 0 ; count < beotles.lenqtb; count-- )
{
olert{beotles[count]);
]
Intake SS - 0S }ulie Iskanuei
2u12-2u1S

2S
If you iun this coue, you will see foui aleit messages, one foi each Beatle.
\H >&%]*#
The 'foi' keywoiu, is useu in two uiffeient ways in }avaSciipt. It is also useu in the
foiin statement.
for {vorioble in object)
stotement
The foi-in loop is useu to iteiate ovei the elements of an aiiay (oi an object).
Let's see an example of using a foi-in to loop thiough the elements of an aiiay.
Take caie that the vaiiable will caiiy each keyinuex of each element not the
value.
<=,6/32I
vor o = ['o', 'b', 'c', 'x', 'y', 'z'];
vor result = 'n';
for {vor i in o)
{
result -= 'inJex: ' - i - ', volue: ' - o[i] - 'n';
]

The iesult is:
"
inJex: 0, volue: o
inJex: 1, volue: b
inJex: 2, volue: c
inJex: S, volue: x
inJex: 4, volue: y
inJex: S, volue: z
"
The foiin statement pioviues a way to loop thiough the piopeities of an object.
The bouy of the foiin loop is executeu once foi each piopeity of object. Befoie
the bouy of the loop is executeu, the name of one of the object's piopeities is
assigneu to vaiiable, as a stiing.
Within the bouy of the loop, you can use this vaiiable to look up the value of the
object's piopeity with the |j opeiatoi.
Foi example, the following foiin loop piints the name anu value of each
piopeity of an object:
Intake SS - 0S }ulie Iskanuei
2u12-2u1S

26
for {vor prop in my_object)
{
Jocument.write{"nome: " - prop - "; volue: " - my_object[prop], "<br~");
]
R(#)$*&#4
A function is a gioup of statements that can be invokeu fiom anywheie in youi
coue, multiple times.
function nome{orquments) {
stotements;
]
<=,6/32I
function sum{x,y)
{
vor c=x-y;
return c;
]
'sum' is the function name(optional)
x,y aie the function input paiameteis that aie passeu to the function on calling it
the ietuin statement states the value ietuineu fiom the function call.
To call this function
vor x=sum{1,2) ,,x will be S;
Any aiguments that aie passeu to a function can be useu just like iegulai
vaiiables within the function.
If a function was uefineu to take paiameteis anu was calleu without them,
}avaSciipt assign the vaiiables with unuefineu.
If you sent moie paiameteis than uefineu, }avaSciipt will just ignoie them.
@,%*,732 4)&/2
A global vaiiable can be iefeienceu fiom anywheie in the sciipt. 0nce a global
vaiiable has been ueclaieu in a sciipt, that vaiiable can be accesseu fiom
anywheie in that sciipt, even within functions. Its scope is L3&7,3.
Intake SS - 0S }ulie Iskanuei
2u12-2u1S

27
A 3&),3 vaiiable exists only within the function in which it is ueclaieu. You can't
access the vaiiable outsiue the function. It has a local scope.
The is no block scope, only function scope. This means that if a vaiiable is uefineu
insiue a function, it's not visible outsiue of the function. Bowevei, a vaiiable
uefineu insiue a 'if' oi a 'foi' coue block is visible outsiue the coue block.
EHJH If you unintentionally use the name of a global vaiiable within a function,
}avaSciipt will assume that you aie iefeiiing to the L3&7,3 vaiiable. 0se the 'vai'
keywoiu to explicitly set the scope of a vaiiable within a function.
If you use vai within a function, the vaiiable will be tieateu as a local vaiiable. It
only exists within the context of the function.
If you uon't use vai, the vaiiable will be tieateu as a global vaiiable.
Take a look at this example:
function squore{num)
{
totol = num * num;
return totol;
]
vor totol = S0;
vor number = squore{20);
olert{totol);
The value of the vaiiable total is now 4uu, which wasn't intenueu. Because insiue
the function total was not ueclaieu with 'vai'.
function squore{num)
{
vor totol = num * num;
return totol;
]

EHJH It is goou piactice to minimize the numbei of global vaiiables useu.

R(#)$*&#4 ,%2 K,$,

They aien't just excutable coue but aie objects. Thus can be assigneu to
vaiiables.
function f{){return 1;]
vor f = function{){return 1;]

Intake SS - 0S }ulie Iskanuei
2u12-2u1S

28
Both uefinitions aie valiu. To call the function we use f();

The seconu way of uefining a function is known as function liteial notation.

?#&#O6&(4 R(#)$*&#4

They aie functions without a function name. They can be assigneu to vaiiables oi
callbacks anu events. They can be passeu as paiameteis to othei functions oi you
can uefine an anonymous function anu execute it iight away.

function{o){return o;]

<=,6/32I
function invoke_onJ_oJJ{o, b)
{
return o{) - b{);
]

function one{) {return 1;]
function two{) {return 2;]
!"#$%&'(")'())*$"&+ -.$/0

0i simply:

invoke_onJ_oJJ{function{){return 1;], function{){return 2;])

When you pass a function A to anothei function B anu B executes A, it's often saiu
that A is a 1(223(1% function. If A uoesn't have a name, then you can say that it's
an ("$"45$67 1(223(1% function.

Why use them.
They let you pass functions without the neeu to name them (which means
theie aie less global vaiiables)
You can uelegate the iesponsibility of calling a function to anothei function
(which means theie is less coue to wiite)
They can help with peifoimance

.23>G*#-&X*#L R(#)$*&#4
Anothei application of an anonymous function is calling this function iight aftei it
was uefineu.
<=,6/32I
{function{){olert{'boo');]){);

Intake SS - 0S }ulie Iskanuei
2u12-2u1S

29
Simply place an anonymous function uefinition insiue paientheses followeu by
anothei set of paientheses. The seconu set basically says "execute now" .
<=,6/32I
{function{nome){olert{'Eello ' - nome - '!');]){'JuJe')

Why use this.
Becieases neeu to cieate global vaiiables.
Suiteu foi one-off oi initialization tasks.

Biawback:
Cannot execute the same function twice (unless you put it insiue a loop oi
anothei function).

912 ^3&7,3 P7S2)$

The host enviionment (web biowsei) pioviues a global object anu all global
vaiiables aie actually piopeities of the global object. The global object is calleu
winuow.
Foi example Beclaiing
vor o = 1;
outsiue of any function, makes it a global vaiiable. Then it can be accesseu:
As a vaiiable a
As a piopeity of the global object,
o winuow|'a'j
o winuow.a

All global functions can also be invokeu as methous of the winuow object.
paiseInt('1u1') oi winuow.paiseInt('1u1 ualmatians').


Refeiences :
i
Fiom http:www.ciockfoiu.comjavasciiptlittle.html
ii
Fiomhttp:web.aichive.oigweb2uu8u2u8124612http:wp.netscape.comcompioucolu
mnstechvisioninnovatois_be.html
iii
Bom Sciipting, Web Besign with }avaSciipt anu the Bocument 0bject Nouel, }eiemy Keith,
2uuS.
iv
0bject 0iienteu }avaSciipt, Stoyan Stefanov, 2uu8, Chaptei 2

Vous aimerez peut-être aussi