31
 JavaScript JavaScript Best Practices Best Practices Sang Shin Sang Shin Java Technology Architect Java Technology Architect Sun Microsystems, Inc. Sun Microsystems, Inc. [email protected] [email protected] www.javapassion.com www.javapassion.com

JavaScript Best Practices

Embed Size (px)

DESCRIPTION

Optimal practices, exercises, and approaches when coding in JavaScript.

Citation preview

  • 5/21/2018 JavaScript Best Practices

    1/31

    JavaScriptJavaScriptBest PracticesBest Practices

    Sang ShinSang Shin

    Java Technology ArchitectJava Technology Architect

    Sun Microsystems, Inc.Sun Microsystems, [email protected]@sun.com

    www.javapassion.comwww.javapassion.com

  • 5/21/2018 JavaScript Best Practices

    2/31

    2

    Disclaimer & Acknowledgments

    Even though Sang Shin is a full-time employee ofSun Microsystems, the contents here are created as

    his own personal endeavor and thus does notnecessarily reflect any official stance of SunMicrosystems on any particular technology

    Acknowledgments

    > The contents of this presentation was created fromJavaScript recommendations for AJA component writers!written "y #reg Murray> https$%%"lueprints&dev&'ava&net%"pcatalog%conventions%'avascript-

    recommendations&html

  • 5/21/2018 JavaScript Best Practices

    3/31

    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

  • 5/21/2018 JavaScript Best Practices

    4/31

    Use Object OrientedUse Object OrientedJavaScriptJavaScript

  • 5/21/2018 JavaScript Best Practices

    5/31

    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

  • 5/21/2018 JavaScript Best Practices

    6/31

    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 (idnamedescprice ! 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&

    '

  • 5/21/2018 JavaScript Best Practices

    7/31

    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 66

    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 price466

  • 5/21/2018 JavaScript Best Practices

    8/31

    Use Object #ierarc$%Use Object #ierarc$%

  • 5/21/2018 JavaScript Best Practices

    9/31

    Use Object #ierarc$ies to Organie

    JavaScript Objects to Avoid 'ame "ollision

    5n JavaScript there is the potential for o"'ect namesto collide> 5n Java language, package names are used to prevent

    naming collisions

    JavaScript does not provide package names likeJava however you can> *hen writing components use o"'ects and o"'ect hierarchies

    to organi.e related o"'ects and prevent naming collision

  • 5/21/2018 JavaScript Best Practices

    10/31,

    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 )"'ect2346%% define art under 9+(E/57TS9+(E/57TS&art 1 function 23 0

    this&items 1 ty3 0 this&items&push2new 5tem2id, >ty334 6

    function 5tem 2id, >ty3 0

    this&id 1 id4 this&>ty 1 >ty4 66%% create an instance of the cart and add an itemvar cart 1 new 9+(E/57TS&art234

    cart&add5tem2?id-@?, 34cart&add5tem2?id-B?, @C34

  • 5/21/2018 JavaScript Best Practices

    11/31

    Use t$e protot%peUse t$e protot%pepropert%propert%

  • 5/21/2018 JavaScript Best Practices

    12/31,2

    Use t$e protot%pe propert%

    (se it to define shared "ehavior and to e:tendo"'ects

    The prototypeproperty is a language feature of

    JavaScript> The property is availa"le on all o"'ects

  • 5/21/2018 JavaScript Best Practices

    13/31,3

    Eample! Usage o+ ,protot%pe- propert%

    function art23 0 this&items 1 < =46

    function 5tem 2id,name,desc,price33 0 this&id 1 id4 this&name 1 name4 this&desc 1 desc4 this&price 1 price46

    %% Smartart e:tends the art o"'ect inheriting its properties and adds a total propertyfunction Smartart23 0 this&total 1 C46Smartart&prototype 1 new art234

  • 5/21/2018 JavaScript Best Practices

    14/31,4

    Eample! Usage o+ ,protot%pe- propert%

    %% 8eclare a shared add5tem and calcualteTotal function and adds them%% as a property of the Smartart prototype mem"er&

    art&prototype&add5tem 1 function2id,name,desc,price3 0 this&items&push2new 5tem2id,name,desc,price3346

    art&prototype&calculateTotal 1 function23 0 for 2var l1C4 l D this&items&length4 l3 0 this&total 1 this&total this&items

  • 5/21/2018 JavaScript Best Practices

    15/31

    .rite re/sable JavaScript.rite re/sable JavaScript

  • 5/21/2018 JavaScript Best Practices

    16/31,6

    .rite re/sable JavaScript

    JavaScript should not "e tied to a specificcomponent unless a"solutely necessary

    onsider not hard coding data in your functions thatcan "e parameteri.ed

  • 5/21/2018 JavaScript Best Practices

    17/31,

    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 applicationDscript 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 6D%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?GD%formG

    Ddiv class1?complete? id1?divH@?GD%divGDdiv class1?complete? id1?divHB?GD%divG

  • 5/21/2018 JavaScript Best Practices

    18/31

    Use object literals asUse object literals as+leible +/nction+leible +/nction

    parametersparameters

  • 5/21/2018 JavaScript Best Practices

    19/31,

    Object (iterals

    )"'ect literals are o"'ects defined using "races 2063that contain a set of comma separated key valuepairs much like a map in Java

    E:ample> 0key@$ ?stringalue?, keyB$ B, keyF$

  • 5/21/2018 JavaScript Best Practices

    20/312

    Eample! Usage o+ Object (iterals as

    parametersfunction 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 makeAJAall2params346

    %% This function does not need to changefunction makeAJAall2params3 0

    var service(+ 1 params&service4 &&&6

  • 5/21/2018 JavaScript Best Practices

    21/312,

    Eample! Usage o+ Object (iterals as

    parameters 0 Anon%mo/s Object (iteralsfunction doSearch23 0 makeAJAall20service(+$ ?foo?, method$ ?get?,

    type$ ?te:t%:ml?,

    call"ack$ function230alert2Icall doneI346 6346function makeAJAall2params3 0

    var re> 1 %% getAJA re>uest4 re>&open2params&service(+, params&method, true34

    re>&onreadystatechange 1 params&call"ack4 &&&6

  • 5/21/2018 JavaScript Best Practices

    22/31

    (oad JavaScript(oad JavaScript

    on Demandon Demand

  • 5/21/2018 JavaScript Best Practices

    23/3123

    (oad JavaScript On Demand

    5f you have a large li"rary or set of li"raries youdonIt need to load everything when a page isloaded

    JavaScript may "e loaded dynamically at runtimeusing a li"rary such as JSA7 or done manually"y using AJA to load JavaScript code and

    calling eval23 on the JavaScript

  • 5/21/2018 JavaScript Best Practices

    24/3124

    Eample! (oad JavaScript On Demand

    %% Suppose the following is captured as cart&'s filefunction art 23 0 this&items 1 < =4

    this&checkout 1 function23 0

    %% checkout logic 66

    ---------------------------------------------------------------------

    %% get cart&'s using an AJA re>uest

    eval2'avascriptTe:t34var cart 1 new art234

    %% add items to the cartcart&checkout234

  • 5/21/2018 JavaScript Best Practices

    25/31

    "lean separation o+"lean separation o+"ontent1 "SS1 and"ontent1 "SS1 and

    JavaScriptJavaScript

  • 5/21/2018 JavaScript Best Practices

    26/3126

    Separation o+ content1 "SS1 and

    JavaScript A rich we" application user interface is made up of

    > content 2KTM+%KTM+3

    >

    styles 2SS3> JavaScript

    Separating the SS styles from the JavaScript is apractice 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

  • 5/21/2018 JavaScript Best Practices

    27/312

    Eample! Bad Practice

    DstyleGLStylesD%styleG

    Dscript type1?te:t%'avascript?G%% JavaScript logicDscriptG

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

  • 5/21/2018 JavaScript Best Practices

    28/312

    Eample! 2ood Practice

    Dlink rel1?stylesheet? type1?te:t%css? href1?cart&css?GDscript type1?te:t%'avascript? src1?cart&'s?GD"odyGThe >uick "rown fo:&&&D%"odyG

  • 5/21/2018 JavaScript Best Practices

    29/31

    )ed/ce t$e sie o+)ed/ce t$e sie o+

    JavaScript +ileJavaScript +ile

  • 5/21/2018 JavaScript Best Practices

    30/31

    3

    )ed/ce t$e sie o+ JavaScript +ile

    emove the white spaces and shortening the namesof varia"les and functions in a file

    *hile in development mode keep your scriptsreada"le so that they may "e de"ugged easier

    onsider compressing your JavaScript resourceswhen you deploy your application

    5f you use a Frd party JavaScript li"rary use thecompressed version if one is provided&> E:ample compression tool$ ShrinkSafe

  • 5/21/2018 JavaScript Best Practices

    31/31

    JavaScriptJavaScriptBest PracticesBest Practices

    Sang ShinSang Shin

    Java Technology ArchitectJava Technology Architect

    Sun Microsystems, Inc.Sun Microsystems, [email protected]@sun.com

    www.javapassion.comwww.javapassion.com