Вы находитесь на странице: 1из 22

1/4/2014

6 Advanced JavaScript Techniques You Should Know

Six Revisions
Skip site navigation Home All Articles Tutorials Freebies About Contact Subscribe: RSS Feed Follow on Twitter
Tw eet 37

6 Advanced JavaScript Techniques You Should


Like 55

Know
Oct 8 2009 by Louis Lazaris | 33 Comments

There have been a number of articles published over the years that discuss best practices techniques for JavaScript. I thought I would go a little bit beyond the scope of those articles and outline a number of advanced techniques and practices that I have personally used or read about that could be invaluable in certain circumstances. This article doesnt necessarily cover every detail of the methods Im describing, but provides an overview, along with code examples, of some practical JavaScript coding techniques.

1. Closures to Extend Variable Scope


Closures in JavaScript are a fairly straightforward concept, and have been discussed online in a number of indepth articles. The fact that they are straightforward doesnt necessarily mean theyre simple however, as seen by the extensive articles that cover the subject. Simply put, closures allow variable scope to be extended past the common scope restrictions of functions. I like the way Jeremy Keith describes closures in his book Bulletproof Ajax :
http://sixrevisions.com/javascript/6-advanced-javascript-techniques-you-should-know/ 1/22

1/4/2014

6 Advanced JavaScript Techniques You Should Know

"Think of closures as a kind of regional scope: broader than local but not as broad as global." To create a closure, you nest a function inside of a function. That inner function has access to all variables in its parent functions scope. This comes in handy when creating methods and properties in object oriented scripts. Here is a simple example that demonstrates the use of a closure:
f u n c t i o nm y O b j e c t ( ){ t h i s . p r o p e r t y 1=" v a l u e 1 " ; t h i s . p r o p e r t y 2=" v a l u e 2 " ; v a rn e w V a l u e=t h i s . p r o p e r t y 1 ; t h i s . p e r f o r m M e t h o d=f u n c t i o n ( ){ m y M e t h o d V a l u e=n e w V a l u e ; r e t u r nm y M e t h o d V a l u e ; } ; } v a rm y O b j e c t I n s t a n c e=n e wm y O b j e c t ( ) ; a l e r t ( m y O b j e c t I n s t a n c e . p e r f o r m M e t h o d ( ) ) ;

The key portions of the script are the nested anonymous function are highlighted in green and the method call in the a l e r tfunction (last line). Because the method in the alert is actually calling a nested function, that method is able to read the value of the variable called n e w V a l u e , even thought that variable is not within the scope of the anonymous function, or method. Developers use closures all the time, probably unknowingly, since a closure is created any time an anonymous function is nested inside another function and utilizes variables from the parent functions scope. The power of the closure is revealed when that method (the inner function) is called, and values that normally wouldnt be accessible are within "regional" scope and are thus able to be used as any other value. See the references below for some deeper explanations of closures and their relation to scope. I also highly recommend you pick up a good advanced JavaScript book that offers a good discussion of the concepts associated with closures. Further Reading Explaining JavaScript scope and closures (Robert Nyman) Closures in JavaScript (James Padolsey) JavasCript Closures at Jibbering.com JavaScript Closures for Dummies

2. Object Literals to Pass Optional Arguments


Here is a handy coding tip to keep in mind when dealing with functions that can accept a large number of optional arguments. Instead of passing the large number of arguments in the conventional fashion, which could unnecessarily complicate the function, you can pass just one argument which ends up being a collection of arguments declared in an object literal. Lets look, first of all, at how we might do this in the typical manner, so we can see the contrast:
f u n c t i o ns h o w S t a t i s t i c s ( n a m e ,t e a m ,p o s i t i o n ,a v e r a g e ,h o m e r u n s ,r b i ){ d o c u m e n t . w r i t e ( " < p > < s t r o n g > N a m e : < / s t r o n g >"+a r g u m e n t s [ 0 ]+" < b r/ > " ) ; d o c u m e n t . w r i t e ( " < s t r o n g > T e a m : < / s t r o n g >"+a r g u m e n t s [ 1 ]+" < b r/ > " ) ; i f( t y p e o fa r g u m e n t s [ 2 ]= = =" s t r i n g " ){
http://sixrevisions.com/javascript/6-advanced-javascript-techniques-you-should-know/ 2/22

1/4/2014

6 Advanced JavaScript Techniques You Should Know

d o c u m e n t . w r i t e ( " < s t r o n g > P o s i t i o n : < / s t r o n g >"+p o s i t i o n+" < b r/ > " ) ; } i f( t y p e o fa r g u m e n t s [ 3 ]= = =" n u m b e r " ){ d o c u m e n t . w r i t e ( " < s t r o n g > B a t t i n gA v e r a g e : < / s t r o n g >"+a v e r a g e+" < b r/ > " ) ; } i f( t y p e o fa r g u m e n t s [ 4 ]= = =" n u m b e r " ){ d o c u m e n t . w r i t e ( " < s t r o n g > H o m eR u n s : < / s t r o n g >"+h o m e r u n s+" < b r/ > " ) ; } i f( t y p e o fa r g u m e n t s [ 5 ]= = =" n u m b e r " ){ d o c u m e n t . w r i t e ( " < s t r o n g > R u n sB a t t e dI n : < / s t r o n g >"+r b i+" < / p > " ) ; } } s h o w S t a t i s t i c s ( " M a r kT e i x e i r a " ) ; s h o w S t a t i s t i c s ( " M a r kT e i x e i r a " ," N e wY o r kY a n k e e s " ) ; s h o w S t a t i s t i c s ( " M a r kT e i x e i r a " ," N e wY o r kY a n k e e s " ," 1 s tB a s e " ,. 2 8 4 ,3 2 ,1 0 1 ) ;

The function above can take up to 6 arguments. The first two arguments are mandatory, so inside the function, we dont check for their existence. The last 4 arguments are not mandatory, so we only display their values if they exist. We call the function 3 different times (last 3 lines), with different numbers of arguments each time. You can see that if the number of passed arguments was in the dozens, or more, the code could look a little messy, and would be harder to maintain, or read. Now lets look at the same code using object literals to pass the arguments:
f u n c t i o ns h o w S t a t i s t i c s ( a r g s ){ d o c u m e n t . w r i t e ( " < p > < s t r o n g > N a m e : < / s t r o n g >"+a r g s . n a m e+" < b r/ > " ) ; d o c u m e n t . w r i t e ( " < s t r o n g > T e a m : < / s t r o n g >"+a r g s . t e a m+" < b r/ > " ) ; i f( t y p e o fa r g s . p o s i t i o n= = =" s t r i n g " ){ d o c u m e n t . w r i t e ( " < s t r o n g > P o s i t i o n : < / s t r o n g >"+a r g s . p o s i t i o n+" < b r/ > " ) ; } i f( t y p e o fa r g s . a v e r a g e= = =" n u m b e r " ){ d o c u m e n t . w r i t e ( " < s t r o n g > A v e r a g e : < / s t r o n g >"+a r g s . a v e r a g e+" < b r/ > " ) ; } i f( t y p e o fa r g s . h o m e r u n s= = =" n u m b e r " ){ d o c u m e n t . w r i t e ( " < s t r o n g > H o m eR u n s : < / s t r o n g >"+a r g s . h o m e r u n s+" < b r/ > " ) ; } i f( t y p e o fa r g s . r b i= = =" n u m b e r " ){ d o c u m e n t . w r i t e ( " < s t r o n g > R u n sB a t t e dI n : < / s t r o n g >"+a r g s . r b i+" < / p > " ) ; } } s h o w S t a t i s t i c s ( { n a m e :" M a r kT e i x e i r a " } ) ; s h o w S t a t i s t i c s ( { n a m e :" M a r kT e i x e i r a " , t e a m :" N e wY o r kY a n k e e s " } ) ; s h o w S t a t i s t i c s ( { n a m e :" M a r kT e i x e i r a " , t e a m :" N e wY o r kY a n k e e s " , p o s i t i o n :" 1 s tB a s e " , a v e r a g e :. 2 8 4 , h o m e r u n s :3 2 , r b i :1 0 1
http://sixrevisions.com/javascript/6-advanced-javascript-techniques-you-should-know/ 3/22

1/4/2014

6 Advanced JavaScript Techniques You Should Know

} ) ;

Technically, this second method of passing the arguments might require a little bit more code, but with a large collection of arguments, there are a few advantages. First, the function itself is simplified because it accepts only one argument (a r g s ), which is a collection of all the values passed from the object literal (n a m e ,t e a m ,p o s i t i o n , etc). Plus, the actual argument values are easy to read, and can easily be understood, updated, or modified, since the correlation between the values and the argument references are more direct. If the function required only a small number of arguments, then this method would not be necessary, and might actually have the opposite effect. So, use this technique sparingly, and only in situations where you foresee the collection of arguments being hard to maintain over time. Further Reading JavaScript Object Literal JavaScript Object Literals Simplified JavaScript and Object Oriented Programming (OOP)

3. Contextual Targeting of DOM Elements


There are sometimes instances where you need to traverse the DOM and gain access to a specific element, or group of elements, but due to certain restrictions, you may not have direct access to the elements via a CSS class name or ID in the HTML code. This might be because of user-generated content produced through a rich text editor, or dynamic content pulled from a database. Whatever the case, its not impossible to access those unidentified DOM elements via JavaScript. Using what I call "contextual targeting", you can gain access to, and modify, almost any element in the DOM. As long as you have a map of the general template that contains the element you want to target, you can access that element and manipulate it the same way you would an element that has a class name or ID. Lets create some basic HTML code that will serve as our example page:
< d i vi d = " h e a d e r " > < h 1 > S i t eT i t l e < / h 1 > < / d i v > < d i vi d = " s i d e b a r " > < u l > < l i > < ah r e f = " # " > T e s t i n g < / a > < / l i > < l i > < ah r e f = " # " > T e s t i n g < / a > < / l i > < l i > < ah r e f = " # " > T e s t i n g < / a > < / l i > < l i > < ah r e f = " # " > T e s t i n g < / a > < / l i > < l i > < ah r e f = " # " > T e s t i n g < / a > < / l i > < l i > < ah r e f = " # " > T e s t i n g < / a > < / l i > < / u l > < / d i v > < d i vi d = " c o n t e n t " > < h 2 > P a g eT i t l e < / h 2 > < p > < ah r e f = " # " > L o r u mI p s u ml i n kh e r e < / a > .P e l l e n t e s q u eh a b i t a n tm o r b i t r i s t i q u es e n e c t u se tn e t u se tm a l e s u a d af a m e sa ct u r p i se g e s t a s . V e s t i b u l u mt o r t o rq u a m ,f e u g i a tv i t a e ,u l t r i c i e se g e t ,t e m p o rs i ta m e t , a n t e .D o n e ce ul i b e r os i ta m e tq u a me g e s t a ss e m p e r . A e n e a nu l t r i c i e sm iv i t a ee s t .M a u r i sp l a c e r a te l e i f e n dl e o .
http://sixrevisions.com/javascript/6-advanced-javascript-techniques-you-should-know/ 4/22

1/4/2014

6 Advanced JavaScript Techniques You Should Know

P e l l e n t e s q u eh a b i t a n tm o r b it r i s t i q u es e n e c t u se tn e t u se tm a l e s u a d a f a m e sa ct u r p i se g e s t a s .V e s t i b u l u mt o r t o rq u a m ,f e u g i a tv i t a e , u l t r i c i e se g e t ,t e m p o rs i ta m e t ,a n t e .D o n e ce ul i b e r os i ta m e tq u a m e g e s t a ss e m p e r .A e n e a nu l t r i c i e sm iv i t a ee s t .M a u r i s p l a c e r a te l e i f e n dl e o . < / p > < p > < s p a ns t y l e = " c o l o r :r e d ; " > P e l l e n t e s q u eh a b i t a n tm o r b i < / s p a n > t r i s t i q u es e n e c t u se tn e t u se tm a l e s u a d af a m e sa ct u r p i se g e s t a s .V e s t i b u l u m t o r t o rq u a m ,f e u g i a tv i t a e ,u l t r i c i e se g e t ,t e m p o rs i ta m e t ,a n t e .D o n e c e ul i b e r os i ta m e tq u a me g e s t a ss e m p e r .A e n e a nu l t r i c i e sm iv i t a ee s t . M a u r i sp l a c e r a te l e i f e n dl e o .P e l l e n t e s q u eh a b i t a n tm o r b it r i s t i q u es e n e c t u s e tn e t u se tm a l e s u a d af a m e sa ct u r p i se g e s t a s .V e s t i b u l u mt o r t o rq u a m , f e u g i a tv i t a e ,u l t r i c i e se g e t ,t e m p o rs i ta m e t ,a n t e .D o n e ce ul i b e r os i t a m e tq u a me g e s t a ss e m p e r .A e n e a nu l t r i c i e sm iv i t a ee s t .M a u r i sp l a c e r a t e l e i f e n dl e o . < / p > < / d i v > < d i vi d = " f o o t e r " > < p > C o p y r i g h t|< ah r e f = " # " > c o n t a c t < / a >|< ah r e f = " # " > p o l i c y < / a >| < ah r e f = " # " > p r i v a c y < / a > < / p > < / d i v >

Using the HTML code above, if we wanted to target all the anchor tags on the page, we could collect them and manipulate them like this:
v a rm y L i n k C o l l e c t i o n=d o c u m e n t . g e t E l e m e n t s B y T a g N a m e ( " a " ) ; f o r( i = 0 ; i < m y L i n k C o l l e c t i o n . l e n g t h ; i + + ){ / /d os o m e t h i n gw i t ht h ea n c h o rt a g sh e r e }

If we wanted to target only the anchor tags in the footer, however, we would target them based on their context, or surrounding elements, like this:
v a rm y F o o t e r E l e m e n t=d o c u m e n t . g e t E l e m e n t B y I d ( " f o o t e r " ) ; v a rm y L i n k s I n F o o t e r=m y F o o t e r E l e m e n t . g e t E l e m e n t s B y T a g N a m e ( " a " ) ; f o r( i = 0 ; i < m y L i n k s I n F o o t e r . l e n g t h ; i + + ){ / /d os o m e t h i n gw i t hf o o t e ra n c h o rt a g sh e r e }

The first line grabs a reference to the footer element. The second line collects all < a >tags inside the footer. Then we loop through them and do what we want with them. Thus, they are accessible even though they are not grouped via class names. You can accomplish the same thing by using node properties, as shown below.
v a rm y L i n k C o l l e c t i o n=d o c u m e n t . g e t E l e m e n t s B y T a g N a m e ( " a " ) ; f o r( i = 0 ; i < m y L i n k C o l l e c t i o n . l e n g t h ; i + + ){ i f( m y L i n k C o l l e c t i o n [ i ] . p a r e n t N o d e . p a r e n t N o d e . i d= = =" f o o t e r " ){ / /d os o m e t h i n gw i t hf o o t e ra n c h o rt a g sh e r e } }

Similar code could be used to target the lone anchor tag inside the "content" section. We could also limit our anchor tag search to include only tags that have the h r e fattribute set, so as to avoid finding any in-page links. We do this by using the g e t A t t r i b u t emethod:
v a rm y L i n k C o l l e c t i o n=d o c u m e n t . g e t E l e m e n t s B y T a g N a m e ( " a " ) ;
http://sixrevisions.com/javascript/6-advanced-javascript-techniques-you-should-know/ 5/22

1/4/2014

6 Advanced JavaScript Techniques You Should Know

f o r( i = 0 ; i < m y L i n k C o l l e c t i o n . l e n g t h ; i + + ){ i f( m y L i n k C o l l e c t i o n [ i ] . g e t A t t r i b u t e ( " h r e f " ) ){ / /d os o m e t h i n gw i t ht h ea n c h o rt a g sh e r e } }

Finally, youll notice that there is a < s p a n >tag with an inline style. The inline style could have been generated through a content management system, so you may not have the ability to edit it directly. You can target all < s p a n >elements with inline styles like this:
v a rm y L i n k C o l l e c t i o n=d o c u m e n t . g e t E l e m e n t s B y T a g N a m e ( " s p a n " ) ; f o r( i = 0 ; i < m y L i n k C o l l e c t i o n . l e n g t h ; i + + ){ i f( m y L i n k C o l l e c t i o n [ i ] . g e t A t t r i b u t e ( " s t y l e " ) ){ / /d os o m e t h i n gw i t ha l la n c h o r st h a th a v ei n l i n es t y l e s } }

The possibilities are endless with contextual targeting, and there are even more options available if youre using a JavaScript library that normalizes browser differences and simplifies DOM manipulation. Further Reading: getElementsByTagName at Sitepoints JavaScript Reference getElementsByTagName at W3Schools

4. Using Namespaces to Prevent Conflicts


If youre doing an extensive amount of raw JavaScript coding and suspect that additions could be made to the same pages youre working on, you can prevent any future conflicts with your code by giving your code its own namespace. Object-oriented JavaScript implements namespace-like principles due to the fact that properties and methods are declared inside of objects, thus there are less likely to be conflicts. A conflict could arise, however, through object names. And very likely, the conflict will occur "silently", thus you may not be alerted to the issue immediately. You can prevent all conflicts by creating a unique namespace. Lets use the s h o w S t a t i s t i c sfunction to demonstrate how we can encapsulate code into its own namespace:
i f( t y p e o fM Y= =" u n d e f i n e d " ){ M Y=n e wO b j e c t ( ) ; M Y . C U S T O M=n e wO b j e c t ( ) ; } M Y . C U S T O M . n a m e s p a c e=f u n c t i o n ( ){ f u n c t i o ns h o w S t a t i s t i c s ( a r g s ){ d o c u m e n t . w r i t e ( " < p > < s t r o n g > N a m e : < / s t r o n g >"+a r g s . n a m e+" < b r/ > " ) ; d o c u m e n t . w r i t e ( " < s t r o n g > T e a m : < / s t r o n g >"+a r g s . t e a m+" < b r/ > " ) ; i f( t y p e o fa r g s . p o s i t i o n= = =" s t r i n g " ){ d o c u m e n t . w r i t e ( " < s t r o n g > P o s i t i o n : < / s t r o n g >"+a r g s . p o s i t i o n+" < b r/ > " ) ; } i f( t y p e o fa r g s . a v e r a g e= = =" n u m b e r " ){ d o c u m e n t . w r i t e ( " < s t r o n g > A v e r a g e : < / s t r o n g >"+a r g s . a v e r a g e+" < b r/ > " ) ;
http://sixrevisions.com/javascript/6-advanced-javascript-techniques-you-should-know/ 6/22

1/4/2014

6 Advanced JavaScript Techniques You Should Know

} i f( t y p e o fa r g s . h o m e r u n s= = =" n u m b e r " ){ d o c u m e n t . w r i t e ( " < s t r o n g > H o m eR u n s : < / s t r o n g >"+a r g s . h o m e r u n s+" < b r/ > " ) ; } i f( t y p e o fa r g s . r b i= = =" n u m b e r " ){ d o c u m e n t . w r i t e ( " < s t r o n g > R u n sB a t t e dI n : < / s t r o n g >"+a r g s . r b i+" < / p > " ) ; } } s h o w S t a t i s t i c s ( { n a m e :" M a r kT e i x e i r a " , t e a m :" N e wY o r kY a n k e e s " , p o s i t i o n :" 1 s tB a s e " , a v e r a g e :. 2 8 4 , h o m e r u n s :3 2 , r b i :1 0 1 } ) ; } M Y . C U S T O M . n a m e s p a c e ( ) ;

The first few lines create the namespace by checking to see if the "M Y " object already exists. This object can be whatever you want it to be. Just pick a name that you dont think will ever be used again. After the M Y object is created, we are then able to create the "C U S T O M " object as a property of the M Yobject. Then our n a m e s p a c efunction becomes a method of the M Y . C U S T O Mobject. Keep in mind that "M Y ", "C U S T O M " and "n a m e s p a c e " can each be your own custom names. I chose these for demonstration purposes. They could be C H E E S E B U R G E R . O N I O N S . p i c k l e sif you want! The s h o w S t a t i s t i c sfunction is exactly the same as in the example earlier that utilizes an object literal to pass in the values. But in this case, the entire function, including the object literal, is encapsulated inside m y . c u s t o m . n a m e s p a c e . The last line invokes the entire function using dot notation, and the function runs exactly the same as it normally would, except that it is protected from conflicting with another function called "s h o w S t a t i s t i c s ". Further Reading: Object Oriented JavaScript: Namespaces (About.com) Namespacing your JavaScript (Dustin Diaz)

5. Hybrid Application Development


You can create powerful JavaScript applications if you use a combination of a JavaScript library and raw JavaScript code. Many JavaScript libraries are used to implement "pretty" animations and other customizable effectssometimes via plugins that often dont require much to be added to them other than some custom values. On the other hand, there may be situations where youll want to accomplish something specificly requested by a client. Maybe its something not available in a library and that requires extensive coding, possibly utilizing Ajax and a variety of DOM methods. There is no point in reinventing the wheel. You can implement your favorite JavaScript library and take advantage of its simplified Ajax calls, DOM methods, and normalization of browser differences. Thus, you can have the advantages of the library, while still creating custom scripts that are specific to your project.
http://sixrevisions.com/javascript/6-advanced-javascript-techniques-you-should-know/ 7/22

1/4/2014

6 Advanced JavaScript Techniques You Should Know

Further Reading: List of JavaScript libraries at Wikipedia 40 Useful JavaScript Libraries (Smashing Magazine) JavaScript Libraries: A directory of tools shaping the new web

6. Rendering Readable HTML


Finally, this is a technique to use in situations that require dozens of lines of HTML code being generated dynamically via JavaScript. Take the following example:
v a rp a g e C o n t a i n e r=d o c u m e n t . g e t E l e m e n t B y I d ( " c o n t a i n e r " ) ; v a rp a g e T i t l e=" C o n t e n tT i t l e " ; v a ra u t h o r B i o=" M r .L o r u mI p s u m " ; v a rp a g e C o n t e n t=" L o r u mi p s u ml i n et e x th e r e .L o r u mi p s u ml i n et e x th e r e . L o r u mi p s u ml i n et e x th e r e .L o r u mi p s u ml i n et e x th e r e . L o r u mi p s u ml i n et e x th e r e .L o r u mi p s u ml i n et e x th e r e . L o r u mi p s u ml i n et e x th e r e .L o r u mi p s u ml i n et e x th e r e . L o r u mi p s u ml i n et e x th e r e . " ; v a rf o o t e r C o n t e n t=" C o p y r i g h t2 0 0 9 " ; v a rH T M L C o d e=' \ n < h 1 > '+p a g e T i t l e+' < / h 1 > \ n < d i vi d = " c o n t e n t " > \ n < p > '+p a g e C o n t e n t+' < / p > \ n < d i vi d = " a u t h o r _ b i o " > \ n < p > '+a u t h o r B i o+ ' < / p > \ n < / d i v > \ n < / d i v > \ n < d i vi d = " f o o t e r " > < p > '+f o o t e r C o n t e n t+' < / p > \ n < / d i v > \ n ' ; p a g e C o n t a i n e r . i n n e r H T M L=H T M L C o d e ;

The line to take note of above is the one that declares the value of the HTMLCode variable. It renders just find in the generated source code, since it utilizes the "new line" character, so it looks like perfectly good HTML. But if this line of code were any longer it would be extremely difficult to read and maintain in the .js file. Here is the same code as above, but implementing a much more organized method of displaying the HTML:
v a rp a g e C o n t a i n e r=d o c u m e n t . g e t E l e m e n t B y I d ( " c o n t a i n e r " ) ; v a rp a g e T i t l e=" C o n t e n tT i t l e " ; v a ra u t h o r B i o=" M r .L o r u mI p s u m " ; v a rp a g e C o n t e n t=" L o r u mi p s u ml i n et e x th e r e .L o r u mi p s u ml i n et e x th e r e . L o r u mi p s u ml i n et e x th e r e .L o r u mi p s u ml i n et e x th e r e . L o r u mi p s u ml i n et e x th e r e .L o r u mi p s u ml i n et e x th e r e . L o r u mi p s u ml i n et e x th e r e .L o r u mi p s u ml i n et e x th e r e . L o r u mi p s u ml i n et e x th e r e . " ; v a rH T M L C o d e= ' \ n '+ ' < h 1 > '+p a g e T i t l e+' < / h 1 > \ n ' ' < d i vi d = " c o n t e n t " > \ n '+ ' < p > '+p a g e C o n t e n t+' < / p > \ n '+ ' < d i vi d = " a u t h o r _ b i o " > \ n '+ ' < p > '+a u t h o r B i o+' < / p > \ n '+ ' < / d i v > \ n ' ' < / d i v > \ n '+
http://sixrevisions.com/javascript/6-advanced-javascript-techniques-you-should-know/ 8/22

1/4/2014

6 Advanced JavaScript Techniques You Should Know

' < d i vi d = " f o o t e r " > '+ ' < p > '+f o o t e r C o n t e n t+' < / p > \ n '+ ' < / d i v > \ n ' ; p a g e C o n t a i n e r . i n n e r H T M L=H T M L C o d e ;

Now the code is much more readable, and conforms to the manner in which HTML is rendered in an actual HTML page. It even includes proper HTML indenting, and still uses the new line character to properly format the outputted HTML.

Conclusion
Although I didnt provide a detailed explanation of every concept dealt with in this collection, I hope this list provided beginning and intermediate JavaScript coders with an overview of a few fairly advanced practical techniques that they can implement in future projects or experiments. Please feel free to comment on any of the techniques Ive mentioned and some specific ways that you have used them in your own applications.

Related Content
JavaScript Debugging Techniques in IE 6 10 Promising JavaScript Frameworks 40 Excellent Resources for JavaScript Coders Related categories: JavaScript and Web Development

About the Author

Louis Lazaris is a freelance web developer based in Toronto, Canada. He blogs about frontend code on Impressive Webs and is a co-author of HTML5 and CSS3 for the Real World, published by SitePoint. You can follow Louis on Twitter or contact him through his website.

33 Comments

Bryant

October 8th, 2009 Great Article! In terms of #4, I like to break up my code using prototypal inheritance, which does essentially the same thing I believe. so:
http://sixrevisions.com/javascript/6-advanced-javascript-techniques-you-should-know/ 9/22

1/4/2014

6 Advanced JavaScript Techniques You Should Know

var test = function(){ this.method1(); this.method2(); } test.prototype.method1 = function(){ //code } test.prototype.method2 = function(){ //code } var testObj = new test();

cancel bubble

October 8th, 2009 I only scanned this document and Im not trying to bust your balls, but for an article on advanced javascript, I have some suggestions (keep in mind these are based solely on scanning this article): for (i=0; i<myLinkCollection.length; i++) would be better as: for (var i=0, len=myLinkCollection.length; i<len; i++) This calculates the length *once*, not on every iteration. MY = new Object(); would be better as MY = {} Use literal notations for objects (and arrays) I'd throw in document.write here as well but I know your coding is just illustrative.

cancel bubble

October 8th, 2009 @Bryant, you can also group your prototype methods in one object: test.prototype = { method1: function() { /*func body*/ }, method2: function() { /*func body*/ }, method3: function() { /*func body*/ },
http://sixrevisions.com/javascript/6-advanced-javascript-techniques-you-should-know/ 10/22

1/4/2014

6 Advanced JavaScript Techniques You Should Know

method4: function() { /*func body*/ } }; This saves you from having to declare each method with test.prototype.

dev_interview

October 8th, 2009 Good article. Douglas Crockford goes over a lot of these techniques in his javascript videos on yahoo blog. Here is a link that has a collection of these javascript videos. http://techvideos.org/javascript/index.html

Chris

October 9th, 2009 RE: 6. Rendering Readable HTML Both contain examples of invalid Javascript. You cannot have a variable go over more than one line unless it is escaped by putting a \ at the end of the line. i.e. this is bad: r pageContent = Lorum ipsum line text here. Lorum ipsum line text here. Lorum ipsum line text here. Lorum ipsum line text here. Lorum ipsum line text here. Lorum ipsum line text here. Lorum ipsum line text here. Lorum ipsum line text here. Lorum ipsum line text here.; this is good: var pageContent = Lorum ipsum line text here. Lorum ipsum line text here.\ Lorum ipsum line text here. Lorum ipsum line text here.\ Lorum ipsum line text here. Lorum ipsum line text here.\ Lorum ipsum line text here. Lorum ipsum line text here.\ Lorum ipsum line text here.; The second example contains a second error on the following line: \n \n + You need a + to join them together.

http://sixrevisions.com/javascript/6-advanced-javascript-techniques-you-should-know/

11/22

1/4/2014

6 Advanced JavaScript Techniques You Should Know

Lucian Lature

October 9th, 2009 #6 Even more readable HTML: var HTMLCode = \ + pageTitle + \ \ + pageContent + \ \ + authorBio +\ \ \ \ + footerContent + \ ;

Lucian Lature

October 9th, 2009 Sorry, the right format is: #6 Even more readable HTML: var HTMLCode = \ <h1> + pageTitle + </h1>\ <div id="content">\ <p> + pageContent + </p>\ <div id="author_bio">\ <p> + authorBio +</p>\ </div>\ </div>\ <div id="footer">\ <p> + footerContent + </p>\ </div>;

carlo

http://sixrevisions.com/javascript/6-advanced-javascript-techniques-you-should-know/

12/22

1/4/2014

6 Advanced JavaScript Techniques You Should Know

October 9th, 2009 I like these techniques. Thanks for sharing!

albert

October 9th, 2009 This way no need to care about line ending var HTMLCode = [ '' , pageTitle , '' '' , '' , pageContent , '' , '' , '' , authorBio , '' , '', '', '' , '' , footerContent , '' , ''].join(\n);

Louis

October 9th, 2009 Regarding the variable spanning multiple lines: It wasnt originally like that, but it seems the code formatting that Jacob uses on Six Revisions causes that to happen. There probably should be a little graphical arrow indicating that the line is continuous, or else let the overflow scroll.

Richard Davies

October 9th, 2009 Re: #6 I find Douglas Crockfords supplant() function (http://javascript.crockford.com/remedial.html) to be invaluable when working with HTML strings in JavaScript. Hows this for readable? var param = {
http://sixrevisions.com/javascript/6-advanced-javascript-techniques-you-should-know/ 13/22

1/4/2014

6 Advanced JavaScript Techniques You Should Know

pageTitle: Content Title, authorBio: Mr. Lorum Ipsum, pageContent: Lorum ipsum line text here. Lorum ipsum line text here. Lorum ipsum line text here. Lorum ipsum line text here. Lorum ipsum line text here. Lorum ipsum line text here. Lorum ipsum line text here. Lorum ipsum line text here. Lorum ipsum line text here. }; var HTMLCode = \ {pageTitle}\ \ {pageContent}\ \ {authorBio}\ \ \ \ {footerContent}\ .supplant(param);

Richard Davies

October 9th, 2009 Lets try this again var param = { pageTitle: "Content Title", authorBio: "Mr. Lorum Ipsum", pageContent: "Lorum ipsum line text here. Lorum ipsum line text here. Lorum ipsum line text here. Lorum ipsum line text here. Lorum ipsum line text here. Lorum ipsum line text here. Lorum ipsum line text here. Lorum ipsum line text here. Lorum ipsum line text here." }; var HTMLCode = %u2018\ <h1>{pageTitle}</h1>\ <div id="content">\ <p>{pageContent}</p>\ <div id="author_bio">\ <p>{authorBio}</p>\ </div>\ </div>\ <div id="footer">\
http://sixrevisions.com/javascript/6-advanced-javascript-techniques-you-should-know/ 14/22

1/4/2014

6 Advanced JavaScript Techniques You Should Know

<p>{footerContent}</p>\ </div>%u2019.supplant(param);

Daniel Einspanjer

October 9th, 2009 Ive always thought that E4X was exceptionally beautiful at solving technique #6. Unfortunately, it is currently only implemented in SpiderMonkey and Rhino which means it is Gecko/Firefox only and hence, minimally useful. :/ var pageTitle = pageTitle; var pageContent = pageContent; var authorBio = authorBio; var footerContent = footerContent; var code = <> <h1>{pageTitle}</h1> <div id=content> <p>{pageContent}</p> <div id=author_bio> <p>{authorBio}</p> </div> </div> <div id=footer> <p>{footerContent}</p> </div> </>; console.log(code.toXMLString());

_phred

October 9th, 2009 How about:

p a g e C o n t a i n e r . i n n e r H T M L=a r r a y ( ' ' , ' '+p a g e T i t l e+' ' , ' ' , ''+p a g e C o n t e n t+' ' , '' , ''+a u t h o r B i o+' ' ,
http://sixrevisions.com/javascript/6-advanced-javascript-techniques-you-should-know/ 15/22

1/4/2014

6 Advanced JavaScript Techniques You Should Know

'' , ' ' , ' ' , ''+f o o t e r C o n t e n t+' ' , ' ' ) . j o i n ( ' \ n ' ) ; p a g e C o n t a i n e r . i n n e r H T M L=H T M L C o d e ;

In case the spacing gets eaten, see the niceness here: http://gist.github.com/206267 I like using backslash to escape the newline, though, I forgot about that one. As far as more substantial HTML output, one might also try something such as Trimpath, a Javascript template language: http://code.google.com/p/trimpath/

CrociDB

October 9th, 2009 Great tips. Thanks. =D

JV

October 9th, 2009 Awsome! I thought I was the only person who did #6. great to see its an accepted standard!

Laurent

October 10th, 2009 What about Singleton pattern for application dev ? I think it becomes really usefull technic when you do something bigger than playing with a form.

JavaScriptic

October 10th, 2009


http://sixrevisions.com/javascript/6-advanced-javascript-techniques-you-should-know/ 16/22

1/4/2014

6 Advanced JavaScript Techniques You Should Know

myMethodValue = newValue; in the 1st example is not necessary. In fact for a better example of the concept you can read http://yuiblog.com/blog/2007/06/12/module-pattern/

SD

October 10th, 2009 very usefulgreat ..thanks a lot

LEo

October 10th, 2009 No, I dont ^^

Phaoloo

October 11th, 2009 JavaScript Object Literal is new and helpful to me. Ive been working with many OOP languages and dunno JavaScript also support this essential feature.

Mateu

October 11th, 2009 Doesnt #4 have a bug? if (typeof MY == undefined) { MY = new Object(); MY.CUSTOM = new Object(); } If MY is defined, but MY.CUSTOM isnt, then the next assignment should fail: MY.CUSTOM.namespace = function() { This would seem like a nitpick, but this would be exactly
http://sixrevisions.com/javascript/6-advanced-javascript-techniques-you-should-know/ 17/22

1/4/2014

6 Advanced JavaScript Techniques You Should Know

the case if you have a set of several JS files in one namespace, and one of them has been included ahead of MY.CUSTOM. FWIW, the idiom Dustin Diaz uses for this check looks cleaner to me: var DED = window.DED || {}; http://www.dustindiaz.com/javascript-private-public-privileged/ As Crockford points out, you shouldnt need to do new Object(), you can just assign an object literal with {}, or even start populating it straight away: if (typeof MY.CUSTOM === undefined) { MY.CUSTOM = { namespace : function() { } }; } adu, Mateu

skim

October 11th, 2009 In your closure example, arent you implicitly making myMethodValue global? I like creating closures this way (without the need to perform a new to the existing object): var myObject = function() { var newValue = this.property1; return { property1 : value1; property2 : value2; performMethod : function() { var myMethodValue = newValue; return myMethodValue; }; } }

Louis
http://sixrevisions.com/javascript/6-advanced-javascript-techniques-you-should-know/ 18/22

1/4/2014

6 Advanced JavaScript Techniques You Should Know

October 13th, 2009 @Mateu: Yes, it looks like youre correct. In this case, probably the easiest thing to do would be to just check the existence of MY.CUSTOM before calling MY.CUSTOM.namespace(). More importantly, I hope the benefits of using some of these techniques was made clear enough. But thanks for spotting that.

techprism

October 16th, 2009 Nice techniques,, helpful to me.

iresha

October 26th, 2009 These are some really advanced techniques.

Lyons Solutions Web Design

November 29th, 2009 seems like Im not the only one who uses the 6th. lol

ruppercut

July 1st, 2010 RE: 6. Rendering Readable HTML Ive found jTemplates (http://jtemplates.tpython.com/) to be helpful.

http://sixrevisions.com/javascript/6-advanced-javascript-techniques-you-should-know/

19/22

1/4/2014

6 Advanced JavaScript Techniques You Should Know

Wilson

January 16th, 2011 Is there a Javascript function to determine if you are connected to the Internet or offline? I use to have a copy of such function years ago but I lost it when my drive failed. It could be a useful thing especially when you are creating an web application.

Marko

February 1st, 2011 #6 is much better to use an array, its a lot faster than concatenating a string. Like this: var html = []; html.push( + title + ); etc.. bla.innerHTML = html.join();

suddip

February 24th, 2011 Further reading you can use this http://www.w3resource.com/javascript/javascript.php

visitor,,,needs help !:)

June 15th, 2011 hi ,,, ive made a button that do something ,, and go to a page , Please anyone can help and , tell me how to make the button open the page in a pup-up ,, or new tab and then , close it self in a time , or just close ,, can any one help me PLEASE !!!!! me email is : maxdelta2009(at)hotmail(dot)com

http://sixrevisions.com/javascript/6-advanced-javascript-techniques-you-should-know/

20/22

1/4/2014

6 Advanced JavaScript Techniques You Should Know

sankar

August 8th, 2011 Hi, I have to submit atleast 2 or 3 advanced concepts in DOT net technology for my half year goal. Request to provide some information on the same. It will be very helpful if you share some avanced concepts..and suggestions also welcome. Thanks in Advnce. Regards, Sankar

Leave a Comment
Name (required) email (will not be published) used for Gravatars (required) Website

Subscribe to the comments on this article.

Submit Comment

Search
http://sixrevisions.com/javascript/6-advanced-javascript-techniques-you-should-know/ 21/22

1/4/2014

6 Advanced JavaScript Techniques You Should Know

Search

Topics
CSS Design Showcase / Inspiration Freebies JavaScript Mobile Photoshop Project Management Resources Tools Tutorials Usability User Interface Web Applications Web Design Web Development Web Standards WordPress

Recent
Businesses Dont Want Websites Anymore Why Clients Arent Interested in Your Proposals 14 Examples of Websites That Use Web Tableaus Designing for Your Objectives A Quick Introduction to Agile UX Design

Partners

Become a Facebook Fan of Six Revisions. Advertise - Contact - RSS Feed Six Revisions.

http://sixrevisions.com/javascript/6-advanced-javascript-techniques-you-should-know/

22/22

Вам также может понравиться