Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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');
}
like image 851
Null Reference Avatar asked Dec 25 '22 10:12

Null Reference


1 Answers

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.

like image 149
Paul Draper Avatar answered Dec 28 '22 07:12

Paul Draper