Search code examples
javascriptfunctionnestedencapsulation

Calling a javascript function within a function


I have seen javascript something like this

var Gallery = function () {

    var helloworld1 = function () {
        alert('hey1');
    }

    var helloworld2 = function () {
        alert('hey2');
    }

    var helloworld3 = function () {
        alert('hey3');
    }
}();

How would I call the helloworlds within this javascript file?

I've tried

  • helloworld1();
  • Gallery.helloworld1();
  • Gallery().helloworld1();

But they don't seem to work.

Also, are there any reasons why I should be writing my javascript in the above manner, rather than just using

function helloworld() {
    alert('hey1');
}

Solution

  • Perhaps you want

    var Gallery = {
    
        helloworld1: function () {
            alert('hey1');
        },
    
        helloworld2: function () {
            alert('hey2');
        },
    
        helloworld3: function () {
            alert('hey3');
        }
    };
    
    Gallery.helloworld2();
    

    or

    var Gallery = function () {
    
        this.helloworld1 = function () {
            alert('hey1');
        }
    
        this.helloworld2 = function () {
            alert('hey2');
        }
    
        this.helloworld3 = function () {
            alert('hey3');
        }
    };
    
    new Gallery().helloworld2();
    

    Also, are there any reasons why I should be writing my javascript in the above manner?

    It namespaces the functions. Everything to do with galleries is in the Gallery object.