Skip to content Skip to sidebar Skip to footer

Function Declaration Within Function Declaration With Same Name Javascript

I've just seen this pattern in javascript: var test = function () { function test(args) { this.properties = args || {}; //etc } } test.prototype.methodName = functi

Solution 1:

It is strange. The "outer" function acts as a constructor, you can use var myTest = new test(); to create a new test.

The inner function, because of JS function-scoping, would only be available within the constructor method. You could call the inner test(...) from within the constructor, but it seems pointless as presumably args should be passed in to the constructor.

What might have been intended is:

var test = function(args) {
    this.properties = args || {}; // you may want to actually parse each arg here
}

test.prototype.someOtherMethod = function() {}

Solution 2:

The first thing to understand here is that functions in JavaScript create new scopes – there is no block scope (yet). So every variable or function declared inside another function is not visible to the outside.

With that in mind: when you define the inner function with the same name of the outer, you lose the ability to call the outer function recursively from itself, by name, because the inner function will "take over" (or "shadow") that name. Inside both functions, test will refer to the inner function, and outside the outer function testalways refer to the outer function.

Since after the function definition you're modifying test.prototype, we can assume test (the outer one) will be used as a constructor. In this case, the inner test can be seen as a "private" method of the constructor, callable only from within the constructor. For detailed examples of this object-oriented use of functions within functions, see James T's answer.

Solution 3:

This is scope.

When you define a variable as a function, it creates function scope.

Inside that function you can declare the same name, because that function is declared within that scope... Take an easier to follow example:

varUser = function()
{
    functionPrivateToScope()
    {
        // A Function Only Accessible Inside This Functionalert( "private" );
    }

    return 
    {
        PublicToScope: function()
        {
            // A Function Accessible From Outside This Functionalert( "public" );
        } 
    }
}

varJames = newUser();
James.PublicToScope(); // Will alert "public"James.PrivateToScope(); // Will fail to do anything

So to explain the answer, the User sets scope, and because you declare the function as above wit the same name, it does not matter.


People do not like me saying this but you can think of this approach as if it were a class in other languages.

varUser = function()
{
}

is like

classUser
{
}

varUser = function()
{
    functionSomething()
    {
    }
}

is like

classUser
{
    private function Something()
    {
    }
}

and finally

varUser = function()
{
    this.Something = function()
    {
    }

    // orreturn {
        Something: function(){}
    }
}

is like

classUser
{
    public function Something()
    {
    }
}

It's alllll about scope. maybe you have a user variable declared as a function and you wish to allow people to get his first name and last name, you would declare these variables or functions as "public"... but what if you wanted to know his diet was good or bad, you may have some complex functions to work it out, but you want to know one thing, good or bad.. you could make all these functions that do ugly stuff private, and then just display the result with a public function...

varUser = function()
{
    functionCalculateDiet()
    {
        // Lots of scary diet calculating stuff comes out with the resultreturn result;
    }

    return
    {
        FirstName: "James",
        LastName: "Poop",
        StandardOfDiet: function()
        {
            returnCalculateDiet();
        }
    }
}

varMyUser = newUser();
alert( MyUser.FirstName );
alert( MyUser.StandardOfDiet() );

Why do you care?

Quantifying it is both easy and hard but here are some good ones...

  • It's neat
  • If you place a pile of chocolates on a table, they'll all get eaten.. but one of them was for you, people are greedy... Only layout on the table what you want them to eat, they can't be greedy then an accidently eat your chocolate
  • It sets you up for class oriented programming
  • It's clear what the programmer meant to do with the code
  • Memory usage (I'm sure there are overheads to declaring more functions public without need to

Finally, and on a very different note, you have a prototype attached to test, so let's go do this for our user example. Imagine we had an array of users:

var users = [
    newUser(),
    newUser()
];

we can iterate over these and get all their usual properties and methods:

for( a in users )
{
    alert( users[ a ].FirstName );
}

But let's say something happens in our application... a user clicks on a button that asks each user if they like fish and chips or not, we now need a new method for the user... We can prototype a new method to all iterations of that variable "user" we created... We could declare it before hand, but then we'd waste memory and maybe confuse future programmers with its presence that is based off of something very specific:

// user clicks button and runs this codeUser.protoype.DoesUserLikeChips = function(){
    // put some code in here that somehow makes this example make sense :)
}

now on every user in your array, you can call this new method... New functionality babehhh!

You may be thinking, why do you not just go users[ a ].DoesUserLikeChips = function(){}... The answer is that it is applied to only that one instance...

Solution 4:

Inner test function is a private function of outer test function. And then a methodName function has been set as public function of outer test function. There are no special thing about naming inner function as outer one.

Post a Comment for "Function Declaration Within Function Declaration With Same Name Javascript"