Vous êtes sur la page 1sur 31

JavaScript

JavaScript
Best Practices
Best Practices
Sang Shin Sang Shin
Java Technology Architect Java Technology Architect
Sun Microsystems, Inc. Sun Microsystems, Inc.
sang.shin@sun.com sang.shin@sun.com
www.javapassion.com www.javapassion.com
2
Disclaimer & Acknowledgments
Even though Sang Shin is a full-time employee of
Sun Microsystems, the contents here are created as
his own personal endeavor and thus does not
necessarily reflect any official stance of Sun
Microsystems on any particular technology
Acknowledgments
>
The contents of this presentation was created from
JavaScript recommendations for AJA component writers!
written "y #reg Murray
> https$%%"lueprints&dev&'ava&net%"pcatalog%conventions%'avascript-
recommendations&html
3
Topics
(se )"'ect-oriented JavaScript
(se )"'ect hierarchy
(se the prototype property
*rite reusa"le JavaScript code
(se )"'ect literals as function parameters
+oad JavaScript on demand
,lean separation of content, ,SS, and JavaScript
-educe the si.e of JavaScript file

Use Object Oriented
Use Object Oriented
JavaScript
JavaScript
5
Use Object Oriented JavaScript
/rovides "etter reusa"ility of the code
Ena"les your o"'ects to "e "etter organi.ed
Allow for dynamic loading of o"'ects
6
Eample! "art Object in JavaScript
%%
// The Cart object above provides basic support for maintaining
// an internal array of Item objects
function Cart( !
this"items # $%&
'
function Item (id(name(desc(price !
this"id # id&
this"name # name&
this"desc # desc&
this"price # price&
'

// Create an instance of the Cart and add items
var cart # ne) Cart(&
cart"items"push(ne) Item(*id+,*(*-aper*(*something you )rite on*(5&
cart"items"push(ne) Item(*id+2*(*-en*( *.omething you )rite )ith*(3&
var total # /&

for (var l # /& l 0 cart"items"length& l11 !
total # total 1 cart"items$l%"price&
'
2
Eample! "omparable Java "ode
pu"lic class ,art 0
private Array+ist items 1 new Array+ist234
pu"lic Array+ist get5tems23 0
return items4
6
6
pu"lic class 5tem 0
private String id4 private String name4 private String desc4 private dou"le price4

pu"lic 5tem2String id, String name, String desc, dou"le price3 0
this&id 1 id4
this&name 1 name4
this&desc 1 desc4
this&price 1 price4
6

pu"lic String get5d23 0return id46
pu"lic String get7ame23 0return name46
pu"lic String get8esc23 0return desc46
pu"lic float get/rice23 0return price46
6


Use Object #ierarc$%
Use Object #ierarc$%
3
Use Object #ierarc$ies to Organi&e
JavaScript Objects to Avoid 'ame "ollision
5n JavaScript there is the potential for o"'ect names
to collide
>
5n Java language, package names are used to prevent
naming collisions
JavaScript does not provide package names like
Java however you can
>
*hen writing components use o"'ects and o"'ect hierarchies
to organi.e related o"'ects and prevent naming collision
,/
Eample! "reate a top level object B(UEP)*'TS w$ic$
acts in a sense like a namespace +or related objects
%% create the "ase 9+(E/-57TS o"'ect if it does not e:ist&
if 2;9+(E/-57TS3 0
var 9+(E/-57TS 1 new )"'ect234
6

%% define ,art under 9+(E/-57TS
9+(E/-57TS&,art 1 function 23 0
this&items 1 <=4
this&add5tem 1 function2id, >ty3 0
this&items&push2new 5tem2id, >ty334
6
function 5tem 2id, >ty3 0
this&id 1 id4
this&>ty 1 >ty4
6
6

%% create an instance of the cart and add an item
var cart 1 new 9+(E/-57TS&,art234
cart&add5tem2?id-@?, A34
cart&add5tem2?id-B?, @C34

Use t$e protot%pe
Use t$e protot%pe
propert%
propert%
,2
Use t$e protot%pe propert%
(se it to define shared "ehavior and to e:tend
o"'ects
The prototype property is a language feature of
JavaScript
>
The property is availa"le on all o"'ects
,3
Eample! Usage o+ ,protot%pe- propert%
function ,art23 0
this&items 1 < =4
6

function 5tem 2id,name,desc,price33 0
this&id 1 id4
this&name 1 name4
this&desc 1 desc4
this&price 1 price4
6
%% Smart,art e:tends the ,art o"'ect inheriting its properties and adds a total property
function Smart,art23 0
this&total 1 C4
6
Smart,art&prototype 1 new ,art234


,4
Eample! Usage o+ ,protot%pe- propert%
%% 8eclare a shared add5tem and calcualteTotal function and adds them
%% as a property of the Smart,art prototype mem"er&
,art&prototype&add5tem 1 function2id,name,desc,price3 0
this&items&push2new 5tem2id,name,desc,price334
6
,art&prototype&calculateTotal 1 function23 0
for 2var l1C4 l D this&items&length4 lEE3 0
this&total 1 this&total E this&items<l=&price4
6
return this&total4
6

%% ,reate an instance of a ,art and add an item
var cart 1 new Smart,art234
cart&add5tem2?id-@?,?/aper?, ?Something you write on?, A34
cart&add5tem2?id-@?,?/en?, ?Soemthing you write with?, F34
alert2?total is$ ? E cart&calculateTotal2334



.rite re/sable JavaScript
.rite re/sable JavaScript
,6
.rite re/sable JavaScript
JavaScript should not "e tied to a specific
component unless a"solutely necessary
,onsider not hard coding data in your functions that
can "e parameteri.ed
,2
Eample! )e/sable JavaScript +/nction
%% The doSearch23 function in this e:ample can "e reused "ecause it is
%% parameteri.ed with the String id of the element, service (-+, and the DdivG
%% to update& This script could later "e used in another page or application

Dscript type1?te:t%'avascript?G
doSearch2service(-+, srcElement, target8iv3 0
var targetElement 1 document&getElement9y5d2srcElement34
var target8ivElement 1 document&getElement9y5d2target8iv34
%% get completions "ased on service(-+ and srcElement&value
%% update the contents of the target8iv element
6
D%scriptG
Dform onsu"mit1?return false4?G
7ame$ Dinput type1?input? id1?acH@? autocomplete1?false?
onkeyup1?doSearch2InameSearchI,IacH@I,IdivH@I3?G
,ity$ Dinput type1?input? id1?acHB? autocomplete1?false?
onkeyup1?doSearch2IcitySearchI,IacHBI,IdivHBI3?G
Dinput type1?"utton? value1?Su"mit?G
D%formG
Ddiv class1?complete? id1?divH@?GD%divG
Ddiv class1?complete? id1?divHB?GD%divG



Use object literals as
Use object literals as
+leible +/nction
+leible +/nction
parameters
parameters
,3
Object (iterals
)"'ect literals are o"'ects defined using "races 2063
that contain a set of comma separated key value
pairs much like a map in Java
E:ample
>
0key@$ ?stringJalue?, keyB$ B, keyF$ <I"lueI,IgreenI,IyellowI=6
)"'ect literals are very handy in that they can "e
used as arguments to a function
)"'ect literals should not "e confused with JS)7
which has similar synta:
2/
Eample! Usage o+ Object (iterals as
parameters
function doSearch2service(-+, srcElement, target8iv3 0
%% ,reate o"'ect literal
var params 1 0service$ service(-+, method$ ?get?, type$ ?te:t%:ml?64
%% /ass it as a parameter
makeAJA,all2params34
6
%% This function does not need to change
function makeAJA,all2params3 0
var service(-+ 1 params&service4
&&&
6

2,
Eample! Usage o+ Object (iterals as
parameters 0 Anon%mo/s Object (iterals
function doSearch23 0
makeAJA,all20service(-+$ ?foo?,
method$ ?get?,
type$ ?te:t%:ml?,
call"ack$ function230alert2Icall doneI346
634
6

function makeAJA,all2params3 0
var re> 1 %% getAJA re>uest4
re>&open2params&service(-+, params&method, true34
re>&onreadystatechange 1 params&call"ack4
&&&
6

(oad JavaScript
(oad JavaScript
on Demand
on Demand
23
(oad JavaScript On Demand
5f you have a large li"rary or set of li"raries you
donIt need to load everything when a page is
loaded
JavaScript may "e loaded dynamically at runtime
using a li"rary such as JSA7 or done manually
"y using AJA to load JavaScript code and
calling eval23 on the JavaScript
24
Eample! (oad JavaScript On Demand
%% Suppose the following is captured as cart&'s file
function ,art 23 0
this&items 1 < =4
this&checkout 1 function23 0
%% checkout logic
6
6
---------------------------------------------------------------------
%% get cart&'s using an AJA re>uest
eval2'avascriptTe:t34
var cart 1 new ,art234
%% add items to the cart
cart&checkout234

"lean separation o+
"lean separation o+
"ontent1 "SS1 and
"ontent1 "SS1 and
JavaScript
JavaScript
26
Separation o+ content1 "SS1 and
JavaScript
A rich we" application user interface is made up of
>
content 2KTM+%KTM+3
>
styles 2,SS3
>
JavaScript
Separating the ,SS styles from the JavaScript is a
practice which will make your code more
managea"le, easier to read, and easier to customi.e
/lace ,SS and JavaScript code in separate files
)ptimi.e the "andwidth usage "y having ,SS and
JavaScript file loaded only once
22
Eample! Bad Practice
DstyleG
LStyles
D%styleG
Dscript type1?te:t%'avascript?G
%% JavaScript logic
DscriptG
D"odyGThe >uick "rown fo:&&&D%"odyG
25
Eample! 2ood Practice
Dlink rel1?stylesheet? type1?te:t%css? href1?cart&css?G
Dscript type1?te:t%'avascript? src1?cart&'s?G

D"odyGThe >uick "rown fo:&&&D%"odyG

)ed/ce t$e si&e o+
)ed/ce t$e si&e o+
JavaScript +ile
JavaScript +ile
3/
)ed/ce t$e si&e o+ JavaScript +ile
-emove the white spaces and shortening the names
of varia"les and functions in a file
*hile in development mode keep your scripts
reada"le so that they may "e de"ugged easier
,onsider compressing your JavaScript resources
when you deploy your application
5f you use a Frd party JavaScript li"rary use the
compressed version if one is provided&
>
E:ample compression tool$ ShrinkSafe

JavaScript
JavaScript
Best Practices
Best Practices
Sang Shin Sang Shin
Java Technology Architect Java Technology Architect
Sun Microsystems, Inc. Sun Microsystems, Inc.
sang.shin@sun.com sang.shin@sun.com
www.javapassion.com www.javapassion.com

Vous aimerez peut-être aussi