Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function declaration within function declaration with same name javascript

Tags:

javascript

I've just seen this pattern in javascript:

var test = function () {
    function test(args) {
       this.properties = args || {}; //etc
    }
}

test.prototype.methodName = function (){} //...etc

What is going on with the function definition; declared once outside and once inside. What is the value of this approach?

like image 664
Stevo Avatar asked Feb 16 '23 07:02

Stevo


1 Answers

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() {}
like image 61
Dan1701 Avatar answered Feb 17 '23 19:02

Dan1701