6 Advanced JavaScript Techniques You Should Know

Embed Size (px)

Citation preview

  • 8/12/2019 6 Advanced JavaScript Techniques You Should Know

    1/22

    1/4/2014 6 Advanced JavaScript Techniques You Should Know

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

    Tweet 37 55Like

    Six RevisionsSkip site navigation

    Home

    All ArticlesTutorialsFreebiesAboutContactSubscribe: RSS FeedFollow on Twitter

    6

    Advanced JavaScript Techniques You ShouldKnow

    Oct 8 2009 by Louis Lazaris | 33 Comments

    There hav e been a number of articles published over the years that discuss best practices techniques for JavaScrip t. I thoug ht 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 incertain circumstances.

    This article doesnt necessarily cover every detail of the methods Im describing, but provides an overview,along with code examples, o f 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 in-depth articles. The fact that they are straightforward doesnt necessarily mean theyre simple however, asseen by the extensive articles that cover the subject.

    Simply put, closures allow variable scope to be extended past the common scope restrictions of functions. Ilike the way Jeremy Keith describes closures in his book Bulletproof Ajax :

    http://sixrevisions.com/category/freebies/http://sixrevisions.com/all-articles/http://sixrevisions.com/http://sixrevisions.com/http://bulletproofajax.com/http://sixrevisions.com/javascript/6-advanced-javascript-techniques-you-should-know/http://twitter.com/sixrevisionshttp://feeds2.feedburner.com/SixRevisionshttp://sixrevisions.com/contact/http://sixrevisions.com/about/http://sixrevisions.com/category/freebies/http://sixrevisions.com/category/tutorials/http://sixrevisions.com/all-articles/http://sixrevisions.com/http://sixrevisions.com/http://twitter.com/search?q=http%3A%2F%2Fsixrevisions.com%2Fjavascript%2F6-advanced-javascript-techniques-you-should-know%2Fhttps://twitter.com/intent/tweet?original_referer=http%3A%2F%2Fsixrevisions.com%2Fjavascript%2F6-advanced-javascript-techniques-you-should-know%2F&related=designinstruct%3AA%20web%20magazine%20for%20designers%20and%20digital%20artists.&text=6%20Advanced%20JavaScript%20Techniques%20You%20Should%20Know&tw_p=tweetbutton&url=http%3A%2F%2Fsixrevisions.com%2Fjavascript%2F6-advanced-javascript-techniques-you-should-know%2F&via=sixrevisions
  • 8/12/2019 6 Advanced JavaScript Techniques You Should Know

    2/22

    1/4/2014 6 Advanced JavaScript Techniques You Should Know

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

    "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 inits parent functions scope. This comes in handy when creating methods and properties in object orientedscripts. Here is a simple example that demonstrates the use of a closure:

    function myObject() { this.property1 = "value1"; this.property2 = "value2"; var newValue = this.property1; this.performMethod = function() { myMethodValue = newValue; return myMethodValue;

    }; } var myObjectInstance = new myObject();

    alert(myObjectInstance.performMethod());

    The key portions of the script are the nested anonymous function are highlighted in green and the method call

    in the alert function (last line). Because the method in the alert is actually calling a nested function, thatmethod is able to read the value of the variable called newValue , even thought that variable is not within thescope of the anonymous function, or method.

    Developers use closures all the time, probably unknowingly, since a closure is created any time an anonymousfunction 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 beaccessible 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 highlyrecommend you pick up a good advanced JavaScript book that offers a good discussion of the conceptsassociated with closures.

    Further Reading

    Explaining JavaScript scope and closures (Robert Nyman)Closures in JavaScript (James Padolsey)JavasCript Closures at Jibbering.comJavaScript 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 couldunnecessarily 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:

    function showStatistics(name, team, position, average, homeruns, rbi) { document.write("

    Name: " + arguments[0] + "
    "); document.write("Team: " + arguments[1] + "
    ");

    if (typeof arguments[2] === "string") {

    http://blog.morrisjohns.com/javascript_closures_for_dummieshttp://www.jibbering.com/faq/faq_notes/closures.htmlhttp://james.padolsey.com/javascript/closures-in-javascript/http://robertnyman.com/2008/10/09/explaining-javascript-scope-and-closures/
  • 8/12/2019 6 Advanced JavaScript Techniques You Should Know

    3/22

    1/4/2014 6 Advanced JavaScript Techniques You Should Know

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

    document.write("Position: " + position + "
    ");}

    if (typeof arguments[3] === "number") { document.write("Batting Average: " + average + "
    "); } if (typeof arguments[4] === "number") { document.write("Home Runs: " + homeruns + "
    "); } if (typeof arguments[5] === "number") { document.write("Runs Batted In: " + rbi + "

    ");

    }}showStatistics("Mark Teixeira");showStatistics("Mark Teixeira", "New York Yankees");showStatistics("Mark Teixeira", "New York Yankees", "1st Base", .284, 32, 101);

    The function above can take up to 6 arguments. The first two arguments are mandatory, so inside thefunction, 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 cansee 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:

    function showStatistics(args) { document.write("

    Name: " + args.name + "
    "); document.write("Team: " + args.team + "
    "); if (typeof args.position === "string") {

    document.write("Position: " + args.position + "
    ");} if (typeof args.average === "number") { document.write("Average: " + args.average + "
    "); } if (typeof args.homeruns === "number") { document.write("Home Runs: " + args.homeruns + "
    "); } if (typeof args.rbi === "number") { document.write("Runs Batted In: " + args.rbi + "

    "); }}

    showStatistics ({ name: "Mark Teixeira"});

    showStatistics ({ name: "Mark Teixeira", team: "New York Yankees"});

    showStatistics ({ name: "Mark Teixeira", team: "New York Yankees", position: "1st Base", average: .284, homeruns: 32, rbi: 101

  • 8/12/2019 6 Advanced JavaScript Techniques You Should Know

    4/22

    1/4/2014 6 Advanced JavaScript Techniques You Should Know

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

    });

    Technically, this second method of passing the arguments might require a little bit more code, but with a largecollection of arguments, there are a few advantages.

    First, the function itself is simplified because it accepts only one argument ( args ), which is a collection of allthe values passed from the object literal ( name , team , position , etc). Plus, the actual argument values areeasy to read, and can easily be understood, updated, or modified, since the correlation between the valuesand the argument references are more direct.

    If the function required only a small number of arguments, then this method would not be necessary, andmight actually have the opposite effect. So, use this technique sparingly, and only in situations where youforesee the collection of arguments being hard to maintain over time.

    Further Reading

    JavaScript Object Literal

    JavaScript Object Literals SimplifiedJavaScript 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 aCSS class name or ID in the HTML code. This might be because of user-generated content producedthrough 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 whatI call "contextual targeting", you can gain access to, and modify, almost any element in the DOM. As long asyou have a map of the general template that contains the element you want to target, you can access thatelement 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:

    Site Title Testing Testing Testing Testing Testing Testing

    Page Title

    Lorum Ipsum link here. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet,

    ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.

    http://www.javascriptkit.com/javatutors/oopjs.shtmlhttp://www.evotech.net/blog/2008/07/javascript-object-literals-a-definition/http://www.dyn-web.com/tutorials/obj_lit.php
  • 8/12/2019 6 Advanced JavaScript Techniques You Should Know

    5/22

    1/4/2014 6 Advanced JavaScript Techniques You Should Know

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

    Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.

    Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.

    Copyright | contact | policy |

    privacy

    Using the HTML code above, if we wanted to target all the anchor tags on the page, we could collect themand manipulate them like this:

    var myLinkCollection = document. getElementsByTagName("a") ; for (i=0;i

  • 8/12/2019 6 Advanced JavaScript Techniques You Should Know

    6/22

    1/4/2014 6 Advanced JavaScript Techniques You Should Know

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

    for (i=0;i

  • 8/12/2019 6 Advanced JavaScript Techniques You Should Know

    7/22

    1/4/2014 6 Advanced JavaScript Techniques You Should Know

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

    } if (typeof args.homeruns === "number") { document.write("Home Runs: " + args.homeruns + "
    "); } if (typeof args.rbi === "number") { document.write("Runs Batted In: " + args.rbi + "

    "); } }

    showStatistics({ name: "Mark Teixeira", team: "New York Yankees", position: "1st Base", average: .284, homeruns: 32, rbi: 101 });}MY.CUSTOM.namespace();

    The first few lines create the namespace by checking to see if the " MY" 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 MYobject is created, we are then able to create the " CUSTOM" object as a property of the MY object. Then our namespace function becomes a method of the MY.CUSTOM object. Keep in mind that " MY", "CUSTOM" and"namespace " can each be your own custom names. I chose these for demonstration purposes. They could

    be CHEESEBURGER.ONIONS.pickles if you want!

    The showStatistics function 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 insidemy.custom.namespace . The last line invokes the entire function using dot notation, and the function runsexactly the same as it normally would, except that it is protected from conflicting with another function called"showStatistics ".

    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 rawJavaScript code. Many JavaScript libraries are used to implement "pretty" animations and other customizableeffectssometimes via plugins that often dont require much to be added to them other than some customvalues.

    On the other hand, there may be situations where youll want to accomplish something specificly requested bya client. Maybe its something not available in a library and that requires extensive coding, possibly utilizingAjax and a variety of DOM methods.

    There is no point in reinventing the wheel. You can implement your favorite JavaScript library and takeadvantage of its simplified Ajax calls, DOM methods, and normalization of browser differences. Thus, youcan have the advantages of the library, while still creating custom scripts that are specific to your project.

    http://www.dustindiaz.com/namespace-your-javascript/http://javascript.about.com/od/objectorientedjavascript/a/oop14.htm
  • 8/12/2019 6 Advanced JavaScript Techniques You Should Know

    8/22

    1/4/2014 6 Advanced JavaScript Techniques You Should Know

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

    Further Reading:

    List of JavaScript libraries at Wikipedia40 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 generateddynamically via JavaScript. Take the following example:

    var pageContainer = document.getElementById("container");var pageTitle = "Content Title";var authorBio = "Mr. Lorum Ipsum";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.";var footerContent = "Copyright 2009";var HTMLCode = '\n' + pageTitle + '\n \n

    ' + pageContent + '

    \n \n

    ' + authorBio +'

    \n \n \n

    ' + footerContent + '

    \n

    \n';pageContainer.innerHTML = HTMLCode;

    The line to take note of above is the one that declares the value of the HTMLCode variable. It renders justfind in the generated source code, since it utilizes the "new line" character, so it looks like perfectly goodHTML. But if this line of code were any longer it would be extremely difficult to read and maintain in the .jsfile.

    Here is the same code as above, but implementing a much more organized method of displaying the HTML:

    var pageContainer = document.getElementById("container");var pageTitle = "Content Title";var authorBio = "Mr. Lorum Ipsum";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.";var HTMLCode = '\n' + '' + pageTitle + '\n'

    '\n' + '

    ' + pageContent + '

    \n' + '\n' + '

    ' + authorBio + '

    \n' + '\n' '\n' +http://javascriptlibraries.com/http://www.smashingmagazine.com/2009/03/02/40-stand-alone-javascript-libraries-for-specific-purposes/http://en.wikipedia.org/wiki/List_of_JavaScript_libraries
  • 8/12/2019 6 Advanced JavaScript Techniques You Should Know

    9/22

    1/4/2014 6 Advanced JavaScript Techniques You Should Know

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

    '' + '

    ' + footerContent + '

    \n' + '\n';

    pageContainer.innerHTML = HTMLCode;

    Now the code is much more readable, and conforms to the manner in which HTML is rendered in an actualHTML 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 practicaltechniques 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 haveused them in your own applications.

    Related Content

    JavaScript Debugging Techniques in IE 610 Promising JavaScript Frameworks40 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 front-end code on Impressive Webs and is a co-author of HTML5 and CSS3 for the Real World , published bySitePoint. 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 thingI believe.

    so:

    http://www.axscollective.com/http://twitter.com/ImpressiveWebshttp://www.sitepoint.com/books/htmlcss1/http://www.impressivewebs.com/http://sixrevisions.com/category/web-development/http://sixrevisions.com/category/javascript/http://sixrevisions.com/resources/40_resources_for_javascript_coders/http://sixrevisions.com/javascript/promising_javascript_frameworks/http://sixrevisions.com/javascript/javascript-debugging-techniques-in-ie-6/
  • 8/12/2019 6 Advanced JavaScript Techniques You Should Know

    10/22

    1/4/2014 6 Advanced JavaScript Techniques You Should Know

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

    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

  • 8/12/2019 6 Advanced JavaScript Techniques You Should Know

    11/22

    1/4/2014 6 Advanced JavaScript Techniques You Should Know

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

    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://www.electrictoolbox.com/http://techvideos.org/javascript/index.htmlhttp://dev-interview-questions.blogspot.com/
  • 8/12/2019 6 Advanced JavaScript Techniques You Should Know

    12/22

    1/4/2014 6 Advanced JavaScript Techniques You Should Know

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

    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 = \ + pageTitle + \\

    + pageContent +

    \\

    + authorBio +

    \\\\

    + footerContent +

    \;

    carlo

    http://lucianlature/http://lucianlature/
  • 8/12/2019 6 Advanced JavaScript Techniques You Should Know

    13/22

    1/4/2014 6 Advanced JavaScript Techniques You Should Know

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

    October 9th, 2009

    I like these techniques. Thanks for sharing!

    albert

    October 9th, 2009

    This way no need to care about line endingvar 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 tohappen. There probably should be a little graphical arrow indicating that the line is continuous, or else let theoverflow scroll.

    Richard Davies

    October 9th, 2009

    Re: #6

    I find Douglas Crockfords supplant() function ( http://javascript.crockford.com/remedial.html ) to beinvaluable when working with HTML strings in JavaScript. Hows this for readable?

    var param = {

    http://javascript.crockford.com/remedial.htmlhttp://www.richarddavies.us/http://www.impressivewebs.com/
  • 8/12/2019 6 Advanced JavaScript Techniques You Should Know

    14/22

    1/4/2014 6 Advanced JavaScript Techniques You Should Know

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

    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\{pageTitle}\\

    {pageContent}

    \\

    {authorBio}

    \\\\http://www.richarddavies.us/
  • 8/12/2019 6 Advanced JavaScript Techniques You Should Know

    15/22

    1/4/2014 6 Advanced JavaScript Techniques You Should Know

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

    {footerContent}

    \%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/Firefoxonly and hence, minimally useful. :/

    var pageTitle = pageTitle;var pageContent = pageContent;var authorBio = authorBio;var footerContent = footerContent;var code = {pageTitle}

    {pageContent}

    {authorBio}

    {footerContent}

    ;

    console.log(code.toXMLString());

    _phred

    October 9th, 2009

    How about:

    pageContainer.innerHTML = array('','' + pageTitle + '',

    '',' ' + pageContent + '',' ',' ' + authorBio + '',

    http://weblog.fredalger.net/https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Processing_XML_with_E4X
  • 8/12/2019 6 Advanced JavaScript Techniques You Should Know

    16/22

    1/4/2014 6 Advanced JavaScript Techniques You Should Know

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

    ' ','','',' ' + footerContent + '','').join('\n');

    pageContainer.innerHTML = HTMLCode;

    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 substantialHTML 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://batailley.net/http://tweetminer.net/http://crocidb.com/http://code.google.com/p/trimpath/http://gist.github.com/206267
  • 8/12/2019 6 Advanced JavaScript Techniques You Should Know

    17/22

    1/4/2014 6 Advanced JavaScript Techniques You Should Know

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

    myMethodValue = newValue; in the 1st example is not necessary. In fact for a better example of the conceptyou 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 dunnoJavaScript 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://www.gigglecomputer.com/http://qtp.blogspot.com/http://yuiblog.com/blog/2007/06/12/module-pattern/
  • 8/12/2019 6 Advanced JavaScript Techniques You Should Know

    18/22

    1/4/2014 6 Advanced JavaScript Techniques You Should Know

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

    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 donew Object(), you can just assign an object literalwith {}, 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://www.impressivewebs.com/http://www.dustindiaz.com/javascript-private-public-privileged/
  • 8/12/2019 6 Advanced JavaScript Techniques You Should Know

    19/22

    1/4/2014 6 Advanced JavaScript Techniques You Should Know

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

    October 13th, 2009

    @Mateu:

    Yes, it looks like youre correct. In this case, probably the easiest thing to do would be to just check theexistence 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 thanksfor 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://jtemplates.tpython.com/http://www.lyonssolutions.co.uk/http://scriptdiaries.blogspot.com/http://inforids.com/
  • 8/12/2019 6 Advanced JavaScript Techniques You Should Know

    20/22

    1/4/2014 6 Advanced JavaScript Techniques You Should Know

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

    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 thingespecially 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 thishttp://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 tomake 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://www.w3resource.com/javascript/javascript.phphttp://webware.o1web.com/
  • 8/12/2019 6 Advanced JavaScript Techniques You Should Know

    21/22

    1/4/2014 6 Advanced JavaScript Techniques You Should Know

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

    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://www.freshbooks.com/?ref=93273http://sixrevisions.com/javascript/6-advanced-javascript-techniques-you-should-know/feed/
  • 8/12/2019 6 Advanced JavaScript Techniques You Should Know

    22/22

    1/4/2014 6 Advanced JavaScript Techniques You Should Know

    Search

    Topics

    CSSDesign Showcase / Inspiration

    FreebiesJavaScriptMobilePhotoshopProject ManagementResourcesToolsTutorialsUsabilityUser InterfaceWeb ApplicationsWeb DesignWeb DevelopmentWeb StandardsWordPress

    Recent

    Businesses Dont Want Websites AnymoreWhy Clients Arent Interested in Your Proposals14 Examples of Websites That Use Web TableausDesigning for Your ObjectivesA Quick Introduction to Agile UX Design

    Partners

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

    http://feeds2.feedburner.com/SixRevisionshttp://sixrevisions.com/contact/http://sixrevisions.com/advertising/http://www.facebook.com/sixrevisionshttp://www.maxcdn.com/http://sixrevisions.com/user-experience-ux/agile-ux-design/http://sixrevisions.com/user-interface/designing-for-objectives/http://sixrevisions.com/design-showcase-inspiration/web-tableaus/http://sixrevisions.com/business/why-clients-arent-interested-in-your-proposals/http://sixrevisions.com/site-news/no-more-websites/http://sixrevisions.com/category/wordpress/http://sixrevisions.com/category/web-standards/http://sixrevisions.com/category/web-development/http://sixrevisions.com/category/web_design/http://sixrevisions.com/category/web-applications/http://sixrevisions.com/category/user-interface/http://sixrevisions.com/category/usabilityaccessibility/http://sixrevisions.com/category/tutorials/http://sixrevisions.com/category/tools/http://sixrevisions.com/category/resources/http://sixrevisions.com/category/project-management/http://sixrevisions.com/category/photoshop/http://sixrevisions.com/category/mobile/http://sixrevisions.com/category/javascript/http://sixrevisions.com/category/freebies/http://sixrevisions.com/category/design-showcase-inspiration/http://sixrevisions.com/category/css/