Javascript function call inside function

I saw javascript something like this

var Gallery = function () {

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

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

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

How can I call helloworld in this javascript file?

I tried

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

But they do not seem to work.

Also, are there any reasons why I should write my javascript in the way above and not just use

function helloworld() {
    alert('hey1');
}
+4
source share
5 answers

Maybe 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 write my javascript as above?

It names functions. Everything related to the galleries is located in the facility Gallery.

+3

, , ( , ). , var function. , .

"", .

, function var, . () function, JavaScript, var.

+3

1- . , Gallery , , undefined. Gallery.helloworld(), .. undefined. Helloworld1() , helloworld1 , . , .

, , .

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

, . , . Gallery.helloworld1(), .

. ,

var Gallery = function(){
    var realGallery = {no_of_pictures:1};
    return {
        getNumberOfPictures:function(){return realGallery.no_of_pictures;},
        increasePictures:function(){realGallery.no_of_pictures += 1;},
        decreasePictures:function(){realGallery.no_of_pictures -= 1;}

    }
}();

, no_of_pictures realGallery. . . , , . , function helloworld() {alert('hey1');} - .   function helloworld(){alert('go away right now !!');}

, - . ​​javascript.

+2

, , Gallery. . , , . 3 hello world functions . , , . .

+1

, , - , , var this.

- . "". , - . , , , - .

, , , - :

var Gallery = function () {

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

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

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

    this.helloworld1 = helloworld1;
    this.helloworld2 = helloworld2;
    this.helloworld3 = helloworld3;

};

var g = new Gallery();
g.helloworld1();

, , ( / this:

var Gallery = function () {

    this.helloworld1 = function () {
        alert('hey1');
    }

    return this;
}();

console.log(Gallery.helloworld2);
+1

Source: https://habr.com/ru/post/1537276/


All Articles