Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 8 of 8
  1. #1
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    2,884
    Thanks
    56
    Thanked 539 Times in 536 Posts

    how do you write production code

    hello,

    I am rewriting some code at the moment and it is written in a style that I am unfamiliar with, which I think is called production style. Here's a very basic example:

    Code:
    <!doctype html>
    <html lang="en">
        
        <head>
    	<style>
    	</style>
        </head>
        
        <body>
    <input type="button" value="hi" onclick="namespace.hello()"/>
    <input type="button" value="bye" onclick="namespace.goodbye()"/> 
    	 <script>
    var namespace = function () {
        return {
            hello: function () {
                alert("hello")
            },
    
            goodbye: function () {
                alert("goodbye")
            }
        }
    }();
    		</script>
        </body>
    </html>
    which works, but I wonder about the return in there - other examples I have seen around the net don't use that return, but if I take it out or try to replace it I get all sorts of errors.

    My questions:

    - Is the return really necessary, and if not how would you make that code work without?

    - I assume that the page is coded that way to avoid polluting the global namespace. But I have two functions within the same page that need access to the same variables. I see that declaring a variable in the "namespace" function makes it available to both the hello and goodbye functions, but it doesn't actually become globally global, does it?

    thanks in advance for any thoughts.

  • #2
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    2,884
    Thanks
    56
    Thanked 539 Times in 536 Posts
    oh, der.

    I think I got it...
    Code:
    var namespace= {
    msg:"howdy",
        
            hello: function () {
                alert(namespace.msg)
            },
    
            goodbye: function () {
                alert("goodbye")
            }
     }
    didn't I?

  • #3
    Regular Coder
    Join Date
    Jan 2013
    Location
    Germany
    Posts
    578
    Thanks
    4
    Thanked 77 Times in 77 Posts
    Yes, both snippets are essentially the same. The second one simply declares an object, the first one is a little bit trickier: It defines a function that returns an object and then immediately calls itself (so-called self-invoking function).
    You're also right about the purpose: Except for the namespace (i.e. the name of your module) nothing will be global, which means that you don't break other code and just as important, other code won't break yours (unless it is loaded after yours and explictly overwrites your namespace object).

    The only thing to look out for now is to ensure that namespaces won't collide. This is already fairly unlikely and even if it happens, it's an easy fix. In other languages like Java, for example, it's common practice to use reverse domain notation as the "namespace" (technically it's more a subpackage structure, but the idea is the same). The Google Play Store even uses this as the unique identification for an app!

    The tricky thing about this in JavaScript is a concept called closures. A simple example:

    Code:
    var counter = (function () { 
        var current = 0; 
        return function () {
            console.log( current++ );
        };
    })();
    
    counter(); // 0
    counter(); // 1
    counter(); // 2
    
    console.log( current ); // undefined
    
    var current = 42;
    
    counter(); // 3
    counter(); // 4
    
    console.log( current ); // 42
    The variable current sort of acts like a private variable: It is within the closure of the self-invoked function and will stay alive in there, so the returned function can keep using it. However, it will be completely unknown to the global scope. Even adding a global variable with the same name will not interfere with this.

  • #4
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,592
    Thanks
    0
    Thanked 645 Times in 635 Posts
    The simplest way to avoid namespace clashes in JavaScript if you don't jumble the JavaScript with the HTML as you have in your example is to wrap all of the code for a script inside an anonymous function so as to effectively create a separate unnamed namespace for that script. Only library references need to use global variables so as to be accessible to multiple scripts in the page.

    For example:

    Code:
    (function() {
    // all your code goes here
    })();
    or if you use JQuery then the following leaves just jQuery as the only global variable while you use $ inside your code to reference it.

    Code:
    jQuery.noConflict();
    (function($) {
    // all your jQuery code goes here
    })(jQuery);
    Where you don't keep all the JavaScript together and instead jumble it with the HTML the way you used to have to do it for Netscape 4 and earlier then setting up a namespace like you have will at least minimize clashes with other scripts in the page - but it will mean that if you have the same piece of HTML on multiple pages and some have one script that references a tag and some have two then the JavaScript embedded in the HTML will need to be different depending on which scripts are attached to the page - so there is still the possibility for script clashes in the part of the script that is in the HTML file instead of in the JavaScript.

    To avoid such clashes you should replace the JavaScript code in the HTML with an id attribute and then add code into the separate JavaScript to run the code you removed from the HTML but using an event listener rather than an event handler - so that having a second script add code for the same event will not cause a clash.

    With the code you currently have using the namespace simply adding a second script that contains the following statement would break the first script even with it using a namespace - because the event processing is outside the namespace.

    Code:
    document.getElementsByTagName('input')[0].onclick = function() {alert('not hello');};
    Last edited by felgall; 02-02-2013 at 03:45 AM.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #5
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    2,884
    Thanks
    56
    Thanked 539 Times in 536 Posts
    Yes, Stephen. I think I have heard you say something similar before. Like I said - it was a basic example. Although I must say I haven't seen this before:
    Quote Originally Posted by felgall View Post
    Code:
    document.getElementsByTagName('input')[0].onclick - function() {alert('not hello');};
    does that remove the function from the onclick event?

  • #6
    Regular Coder
    Join Date
    Jan 2013
    Location
    Germany
    Posts
    578
    Thanks
    4
    Thanked 77 Times in 77 Posts
    I'm invisible.

  • #7
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    2,884
    Thanks
    56
    Thanked 539 Times in 536 Posts
    sorry, Airblader. Thank you for your detailed explanation. It clears up many mysteries for me

  • Users who have thanked xelawho for this post:

    Airblader (02-01-2013)

  • #8
    Senior Coder
    Join Date
    Apr 2011
    Location
    London, England
    Posts
    2,120
    Thanks
    15
    Thanked 354 Times in 353 Posts
    Quote Originally Posted by xelawho View Post
    Yes, Stephen. I think I have heard you say something similar before. Like I said - it was a basic example. Although I must say I haven't seen this before:


    does that remove the function from the onclick event?
    It's just a typo, should be "=" not "-".
    "I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
    Validate your HTML and CSS


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •