How to Create Javascript Objects

It is easy to create Javascript objects, but this method goes one step further by allowing you to create a Javascript object with private and public methods, as well as private variables. It’s a perfect way to create a single access point for Javascript and Flash to communicate.

The project I’m currently working on requires heavy interaction between a Flash object and the HTML/DOM. Links on the page need to call methods on the Flash object, and events in the Flash object need to trigger actions on the page.

I decided to create a DOM/Flash Connector in Javascript that would expose all of the methods that each can call into the other. I wanted it to be fully encapsulated, and as object oriented as possible.

One example of what it needed to do was show extended content (in HTML) that the Flash object was not large enough to display. For example, when a photo is displayed within the Flash object, the photo’s title, description, comments, tags, rating, etc. is displayed in HTML below the Flash object.

Here is the method I chose to use:

var Connector = function(){

    var _flashElSelector = false;
    var _flashIsReady    = false;
    var _flash           = null;

    // load html into extended content area
    // this is a "private" method in the Connector class
    // it can only be called from within the returned object
    var _populateExtendedContent = function(url, data){
        $('#extendedcontent').load(url, data);

    return {

        // initialize connector object
        // set the jQuery selector to be used for retrieving 
        // the Flash object element
        init : function(selector){
            _flashElSelector  = selector;

        // flash is ready
        // flash calls this method as soon as it is ready to accept
        // incoming method calls
        flashReady : function(){
            // find flash object in DOM
            _flash        = $(_flashElSelector).get(0);
            _flashIsReady = true;

        // show content for specified ID in extended content area
        showExtendedContent : function(id){
            // call the "private" method to display content in the
            // HTML part of the site
            _populateExtendedContent('/show/extendedcontent', {id : id} );

         * Flash Methods

        // show content for specified ID in Flash object
        showContent : function(id){

            // if flash isn't ready to accept method calls, ignore
            // this request

                // call the showContent() method on the Flash object
                // this is a method that is exposed by Flash that will
                // display content, based on the content's ID

                // call the showExtendedContent() method on the Connector
                // in this case, "this" refers to the same object as the
                // global "Connector" does
                // displays the extended content in the HTML area of the site



// closure

// set the jQuery selector for retrieving the Flash object
// this is done on the individual pages that have Flash to allow
// for different IDs for the Flash objects on each page

If the user selected some content to be displayed within the Flash object, Flash would call to the connector as follows to display the extended information for the content in HTML.


If the user selected some content to be displayed within the HTML part of the site, Javascript would call to the connector as follows to display the content in Flash and the extended information for the content in HTML.


Note that since the function being assigned to Connector has the (); at the end of it (line 67), it gets executed immediately. This function then returns an object that contains several functions and is assigned to the Connector variable. All of the variables and functions within Connector, that are not returned, are private and inaccessible from the global scope, but fully accessible from within the Connector, as evidenced by line 36.

If you have any questions regarding the script please feel free to post them here in the comments. I’m sure there are many other ways of creating Javascript objects, so please share your thoughts.

24 thoughts on “How to Create Javascript Objects

  1. Thanks for posting this. I think this sums up the best way to create object oriented javascript with ability for private methods and properties.

    I have been trying out RightJS (, which uses a Class object whereby you can create classes and extend those to other classes, and it also has the ability to encapsulate an Options class which provides a uniform way to pass options to your objects. I kind of like this way a little better because it is a little simpler.

    The line number you reference are off by one.

    Also, in line 38, could you use this.populateExtendedContent() (add the keyword “this”)? Do you have a preference on using “this” to indicate that it is a method of this object? And what about prefixing the private methods with an underscore? That might reduce maintenance headaches later on to help keep it straight which are public and private methods.

  2. @Jansen Price
    I fixed the line numbers. Thanks.

    Regarding adding this to the populateExtendedContent() call, this will not work. I think this is where this method of creating objects differs from normal OO programming, since this refers to the object that is being returned by the function. The private methods and variables are outside of the scope of this when in the Connector.

    I do like your idea of following common programming standards and prefixing the private variables and methods with underscores. I have updated the code to do this.

  3. I’ve started using this style in my code as well. One stylistic choice I’ve found very useful when assigning a variable that’s the result of an anonymous function like ‘Connection’ is above is to wrap the function in parentheses.

    //You have to scroll down to the bottom of the function definition
    //before being able to tell if Connector is the function or its result
    var Connector = function() {


    //Here the parens make it more obvious that it’s not just a simple
    //assignment of a function
    var Connector = (function() {


    It’s identical in meaning, but the parens convey pretty clearly that something is going on. I’ve seen this style a few places and it seems as though this is becoming the suggested coding style.

  4. A good example of programming “into” a language instead of programming “in it” :)

    If private methods don’t exist in the language, invent them.

  5. What i don’t realize is in reality how you’re no longer actually a lot more smartly-preferred than you may be right now.

    You are so intelligent. You realize thus significantly with regards
    to this subject, made me for my part believe it from a lot of numerous angles.
    Its like men and women are not interested except it’s something
    to accomplish with Girl gaga! Your personal stuffs nice.

    At all times handle it up!

  6. There are numerous explanations why a tree solution is such an excellent service to make use of about getting a stump removed from your premises. Here are a few associated with big points that you ought to have a look at. They’re all important things that may help you making it easier for you to take care of your yard.

    Cabling is mainly employed for reinforcing weak spots in a tree. An arborist will determine the correct places in the tree to secure cables. This can help a split trunk from being torn aside during storms. It can benefit train big branches to develop upwards instead of downwards. Holes are drilled within the trunks or limbs and a cable is set up. Tension in cable can help contain the two closer together and give them some extra support during wind or rain storms. This may additionally offer power to trees that’ll never be in a position to withstand the weight of ice through the winter. Sometimes rods may be put inside of the limbs for added support. Regular corrections are created to the cables and rods to simply help extend the life of the tree.
    Today, the environment is getting serious menace from cutting and chopping down of trees. That is occurring because individuals are less caring about woods and saving wildlife. But there are numerous people nowadays who realize that without woods, this globe are certain to get extinguished. Have you been sincere about about our planet? If that’s the case, then it’s time for you really to try to find houstons tree experts provider. Caring woods will not means you have to get deep in to the forest and water woods and care them by manure. No, you can try down inside yard and lawn.
    Website location is important to stop harm from wind. If you choose a place which confronted with breeze make certain you make use of a plant that can tolerate high winds. If you can, offer some form of windbreak.

    It is Cheaper! Most tree cutting solution costs are reduced in the winter months because this is a slow period. Local houstons tree experts cost is extremely competitive during this season.

    Over the course of the investigation that then followed this tragedy, several conflicting stories emerged. In an endeavor of find out precisely happened, Ben Geiger Sr. hired a CSI investigator to re-enact the accident.
    Austin therefore the surrounding area has more oak trees and much more reported cases of oak wilt than any area of Texas. If you suspect oak wilt, it is rather important to call an Austin tree service provider and also a professional tackle the duty of containing the fungus.

  7. Hi Your main web page starts up seriously slow in my situation, I’m not sure who’s problem is that but youtube starts up fairly quick.
    Well, I have to appreciate you for putting amazing post.

    I’m assuming it has already been useful to lots of
    individuals . I hope I will be able to get a lot more remarkable stuff and I also really should complement by stating
    you’ve done remarkable writing. I already have you saved to
    my bookmarks to check out blogs you publish.

  8. Preparing a wedding budget can be a difficult process. Perhaps the crowning moment
    came when she Tweeted that, “People are calling this ‘brilliant self-marketing. 47) Night Ranger – “(You Can Still) Rock In America”.

  9. Excellent content. If only all information I found turned out to be just as exceptional. Continue the nice effort.

  10. I’m sure most would agree that this is what you call content. It’s direct and also right to the point. Alot of different blogs go on and on about basically nothing but this specific posting is extremely engaging.

  11. Now i’m really delighted I came across this post. It’s well written and the content is excellent. I hope to uncover more like this.

  12. You can hardly come across content such as this anymore. I recall when you could find one or two topics similar to this in minutes however now it’s substantially more difficult.

  13. Judging by the amount of comments, this really is undeniably an extremely involved topic. Whenever I return to this post there’s an interesting visitor post better than some of the prior ones.

  14. Based on the amount of opinions, this really is undeniably a very engaging subject. Everytime I come back to this post there’s an interesting visitor post better than many of the earlier ones.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>