Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private functions in JavaScript

In a jQuery-based web application I have various script where multiple files might be included and I'm only using one of them at a time (I know not including all of them would be better, but I'm just responsible for the JS so that's not my decision). So I'm wrapping each file in an initModule() function which registers various events and does some initialization etc.

Now I'm curious if there are any differences between the following two ways of defining functions not cluttering the global namespace:

function initStuff(someArg) {
    var someVar = 123;
    var anotherVar = 456;

    var somePrivateFunc = function() {
        /* ... */
    }

    var anotherPrivateFunc = function() {
        /* ... */
    }

    /* do some stuff here */
}

and

function initStuff(someArg) {
    var someVar = 123;
    var anotherVar = 456;

    function somePrivateFunc() {
        /* ... */
    }

    function anotherPrivateFunc() {
        /* ... */
    }

    /* do some stuff here */
}
like image 697
ThiefMaster Avatar asked Nov 19 '10 12:11

ThiefMaster


People also ask

What are private functions in JavaScript?

A private function can only be used inside of it's parent function or module. A public function can be used inside or outside of it. Public functions can call private functions inside them, however, since they typically share the same scope.

Are there private functions in JavaScript?

JavaScript allows you to define private methods for instance methods, static methods, and getter/setters. The following shows the syntax of defining a private instance method: class MyClass { #privateMethod() { //... } }

What is a private function?

Private function means any gathering of persons for the purpose of deliberation, education, instruction, entertainment, amusement, or dining that is not intended to be open to the public and for which membership or specific invitation is a prerequisite to entry.

What is private and public in JavaScript?

Public: These members of the class and available to everyone that can access the (owner) class instance. Private: These members are only accessible within the class that instantiated the object. Protected: This keyword allows a little more access than private members but a lot less than the public.


1 Answers

The major difference between these two approaches resides in the fact WHEN the function becomes available. In the first case the function becomes available after the declaration but in the second case it's available throughout the scope (it's called hoisting).

function init(){
    typeof privateFunc == "undefined";
    var privateFunc = function(){}
    typeof privateFunc == "function";
}

function init(){
    typeof privateFunc == "function";
    function privateFunc(){}
    typeof privateFunc == "function";
}

other than that - they're basically the same.

like image 106
Andris Avatar answered Sep 21 '22 06:09

Andris