Search code examples
javascriptfunctionoopcallinternal

How Can One Javascript Enclosure Internal Function Call Another Internal Function


How can func2 call func1 within the same Javascript enclosure? Is this even possible?

var x = (function() {

    return {
        func1: function func1() {},
        func2: function func2() {
            var y = func1();  // Doesn't work! What does?
        }
    }

}());

Solution

  • Define func1 before you return, then assign a reference to func1 as a property of your return object.

    var x = (function() {
        function func1() {}
    
        return {
            func1: func1,
            func2: function func2() {
                var y = func1();
            }
        }
    
    }());